diff --git a/.github/workflows/gallery.yml b/.github/workflows/gallery.yml index fbd1e1dcf8..53933e40d9 100644 --- a/.github/workflows/gallery.yml +++ b/.github/workflows/gallery.yml @@ -24,7 +24,7 @@ jobs: - name: Install and cache PowerShell modules uses: potatoqualitee/psmodulecache@v5.2 with: - modules-to-cache: dbatools.library:2023.5.5 + modules-to-cache: dbatools.library:2023.9.21 - name: Download dbatools from Gallery run: | diff --git a/.github/workflows/integration-tests-repl.yml b/.github/workflows/integration-tests-repl.yml new file mode 100644 index 0000000000..d7371ad1aa --- /dev/null +++ b/.github/workflows/integration-tests-repl.yml @@ -0,0 +1,152 @@ +name: Run Replication Tests +on: [push] +defaults: + run: + shell: pwsh +jobs: + repl-tests-part1: + runs-on: ubuntu-latest + env: + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} + + steps: + - uses: actions/checkout@v3 + + - name: Install and cache PowerShell modules + uses: potatoqualitee/psmodulecache@v5.2 + with: + modules-to-cache: dbatools.library:2023.5.5 + + - name: Set encryption values + run: | + Import-Module ./dbatools.psd1 -Force + Set-DbatoolsConfig -FullName sql.connection.trustcert -Value $true -Register + Set-DbatoolsConfig -FullName sql.connection.encrypt -Value Optional -Register + Get-DbatoolsConfigValue -FullName sql.connection.encrypt | Write-Warning + + - name: Setup docker images + run: | + # create a shared network + docker network create localnet + # Expose engine and endpoint then setup a shared path for migrations + docker run -p 1433:1433 --volume shared:/shared:z --name mssql1 --hostname mssql1 --network localnet -d dbatools/sqlinstance + # Expose second engine and endpoint on different port + docker run -p 14333:1433 --volume shared:/shared:z --name mssql2 --hostname mssql2 --network localnet -d dbatools/sqlinstance2 + + - name: Add hostname to hosts file + run: | + echo "127.0.0.1 mssql1 mssql2" | sudo tee -a /etc/hosts + + - name: 👥 Clone appveyor repo + working-directory: /tmp + run: | + gh repo clone dataplat/appveyor-lab + + - name: Setup Replication + run: | + Import-Module ./dbatools.psd1 -Force + # need some folders for our repl stuff + docker exec mssql1 mkdir /shared/data /shared/repldata /var/opt/mssql/ReplData + + - name: Run replication tests part 1 + run: | + Import-Module ./dbatools.psd1 -Force + $null = Invoke-Pester ./tests/gh-actions-repl-1.ps1 -Output Detailed -PassThru -Verbose + + repl-tests-part2: + runs-on: ubuntu-latest + env: + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} + + steps: + - uses: actions/checkout@v3 + + - name: Install and cache PowerShell modules + uses: potatoqualitee/psmodulecache@v5.2 + with: + modules-to-cache: dbatools.library:2023.5.5 + + - name: Set encryption values + run: | + Import-Module ./dbatools.psd1 -Force + Set-DbatoolsConfig -FullName sql.connection.trustcert -Value $true -Register + Set-DbatoolsConfig -FullName sql.connection.encrypt -Value Optional -Register + Get-DbatoolsConfigValue -FullName sql.connection.encrypt | Write-Warning + + - name: Setup docker images + run: | + # create a shared network + docker network create localnet + # Expose engine and endpoint then setup a shared path for migrations + docker run -p 1433:1433 --volume shared:/shared:z --name mssql1 --hostname mssql1 --network localnet -d dbatools/sqlinstance + # Expose second engine and endpoint on different port + docker run -p 14333:1433 --volume shared:/shared:z --name mssql2 --hostname mssql2 --network localnet -d dbatools/sqlinstance2 + + - name: Add hostname to hosts file + run: | + echo "127.0.0.1 mssql1 mssql2" | sudo tee -a /etc/hosts + + - name: 👥 Clone appveyor repo + working-directory: /tmp + run: | + gh repo clone dataplat/appveyor-lab + + - name: Setup Replication + run: | + Import-Module ./dbatools.psd1 -Force + # need some folders for our repl stuff + docker exec mssql1 mkdir /shared/data /shared/repldata /var/opt/mssql/ReplData + + - name: Run replication tests part 2 + run: | + Import-Module ./dbatools.psd1 -Force + $null = Invoke-Pester ./tests/gh-actions-repl-2.ps1 -Output Detailed -PassThru -Verbose + + repl-tests-part3: + runs-on: ubuntu-latest + env: + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} + + steps: + - uses: actions/checkout@v3 + + - name: Install and cache PowerShell modules + uses: potatoqualitee/psmodulecache@v5.2 + with: + modules-to-cache: dbatools.library:2023.5.5 + + - name: Set encryption values + run: | + Import-Module ./dbatools.psd1 -Force + Set-DbatoolsConfig -FullName sql.connection.trustcert -Value $true -Register + Set-DbatoolsConfig -FullName sql.connection.encrypt -Value Optional -Register + Get-DbatoolsConfigValue -FullName sql.connection.encrypt | Write-Warning + + - name: Setup docker images + run: | + # create a shared network + docker network create localnet + # Expose engine and endpoint then setup a shared path for migrations + docker run -p 1433:1433 --volume shared:/shared:z --name mssql1 --hostname mssql1 --network localnet -d dbatools/sqlinstance + # Expose second engine and endpoint on different port + docker run -p 14333:1433 --volume shared:/shared:z --name mssql2 --hostname mssql2 --network localnet -d dbatools/sqlinstance2 + + - name: Add hostname to hosts file + run: | + echo "127.0.0.1 mssql1 mssql2" | sudo tee -a /etc/hosts + + - name: 👥 Clone appveyor repo + working-directory: /tmp + run: | + gh repo clone dataplat/appveyor-lab + + - name: Setup Replication + run: | + Import-Module ./dbatools.psd1 -Force + # need some folders for our repl stuff + docker exec mssql1 mkdir /shared/data /shared/repldata /var/opt/mssql/ReplData + + - name: Run replication tests part 3 + run: | + Import-Module ./dbatools.psd1 -Force + Invoke-Pester ./tests/gh-actions-repl-3.ps1 -Output Detailed -PassThru -Verbose diff --git a/.github/workflows/integration-tests.yml b/.github/workflows/integration-tests.yml index 67a169442b..7c12604ba1 100644 --- a/.github/workflows/integration-tests.yml +++ b/.github/workflows/integration-tests.yml @@ -21,7 +21,7 @@ jobs: - name: Install and cache PowerShell modules uses: potatoqualitee/psmodulecache@v5.2 with: - modules-to-cache: dbatools.library:2023.5.5 + modules-to-cache: dbatools.library:2023.9.21 - name: Set encryption values run: | @@ -71,7 +71,7 @@ jobs: uses: potatoqualitee/psmodulecache@v5.2 with: shell: powershell, pwsh - modules-to-cache: dbatools.library:2023.5.5 + modules-to-cache: dbatools.library:2023.9.21 - name: Install SQL Server localdb uses: potatoqualitee/mssqlsuite@v1.3 diff --git a/.github/workflows/xplat-import.yml b/.github/workflows/xplat-import.yml index 1041afe1f5..8c18daedf6 100644 --- a/.github/workflows/xplat-import.yml +++ b/.github/workflows/xplat-import.yml @@ -18,7 +18,7 @@ jobs: - name: Install and cache PowerShell modules uses: potatoqualitee/psmodulecache@v5.2 with: - modules-to-cache: dbatools.library:2023.5.5 + modules-to-cache: dbatools.library:2023.9.21 - name: Perform the import shell: pwsh diff --git a/ReplicationDemo.ps1 b/ReplicationDemo.ps1 new file mode 100644 index 0000000000..4205c4445f --- /dev/null +++ b/ReplicationDemo.ps1 @@ -0,0 +1,99 @@ +# dbatools 💜 dbatools + +############################## +# create docker environment +############################## +# create a shared network +docker network create localnet + +# Expose engines and setup shared path for migrations +docker run -p 2500:1433 --volume shared:/shared:z --name mssql1 --hostname mssql1 --network localnet -d dbatools/sqlinstance +docker run -p 2600:1433 --volume shared:/shared:z --name mssql2 --hostname mssql2 --network localnet -d dbatools/sqlinstance2 + +# create the repl folder +docker exec mssql1 mkdir /var/opt/mssql/ReplData + +# also need these folders for setting up replication +docker exec mssql1 mkdir /shared/data /shared/repldata + +############################## + +# import out version of the module +cd C:\GitHub\DMM-GitHub\dbatools +Import-Module .\dbatools.psd1 + +# lets save the password for connecting to containers because I'm lazy +$securePassword = ('dbatools.IO' | ConvertTo-SecureString -AsPlainText -Force) +$credential = New-Object System.Management.Automation.PSCredential('sqladmin', $securePassword) + +$PSDefaultParameterValues = @{ + "*:SqlCredential" = $credential + "*:DestinationCredential" = $credential + "*:DestinationSqlCredential" = $credential + "*:SourceSqlCredential" = $credential + "*:PublisherSqlCredential" = $credential +} + +# what do we have so far +Get-DbaReplServer -SqlInstance mssql1 +Get-DbaReplDistributor -SqlInstance mssql1 +Get-DbaReplPublisher -SqlInstance mssql1 + +# enable distribution +Enable-DbaReplDistributor -SqlInstance mssql1 + +# enable publishing +Enable-DbaReplPublishing -SqlInstance mssql1 + +# create a transactional publication using splat format +$pub = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'testPub' + Type = 'Transactional' +} +New-DbaReplPublication @pub + +# add an article to the publication +$article = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'testpub' + Name = 'authors' +} +Add-DbaReplArticle @article + +# create a pubs database on mssql2 to replicate to +New-DbaDatabase -SqlInstance mssql2 -Name pubs + +# if you don't the New-DbaReplSubscription command will create the database for you + +# add a subscription to the publication +$sub = @{ + SqlInstance = 'mssql2' + Database = 'pubs' + PublicationDatabase = 'pubs' + PublisherSqlInstance = 'mssql1' + PublicationName = 'testpub' + Type = 'Push' + SubscriptionSqlCredential = $credential + +} +New-DbaReplSubscription @sub + +# creates the snapshot job with a daily schedule at 8am - is that expected? good default? +# should adding a subscription kick off snapshot? should that be an param -StartSnapshotNow -- yes + # create that without a schedule by default maybe a param for a schedule + # + +# stats on the subscription - in the distribution database + # could we make a command to get stats + + + + + + ## when adding an article - we need the options + # - action if name is in use 'drop existing object and create new' + # copy nonclusterd indexes + # nuno diff --git a/bin/dbatools-buildref-index.json b/bin/dbatools-buildref-index.json index bad31c29ee..33ad710f19 100644 --- a/bin/dbatools-buildref-index.json +++ b/bin/dbatools-buildref-index.json @@ -1,5 +1,5 @@ { - "LastUpdated": "2023-06-15T00:00:00", + "LastUpdated": "2023-09-14T00:00:00", "Data": [ { "Version": "8.0.47", @@ -4510,6 +4510,11 @@ "Version": "15.0.4316", "KBList": "5025808" }, + { + "CU": "CU22", + "Version": "15.0.4322", + "KBList": "5027702" + }, { "Version": "16.0.100", "Name": "2022" @@ -4555,6 +4560,21 @@ "CU": "CU5", "Version": "16.0.4045", "KBList": "5026806" + }, + { + "CU": "CU6", + "Version": "16.0.4055", + "KBList": "5027505" + }, + { + "CU": "CU7", + "Version": "16.0.4065", + "KBList": "5028743" + }, + { + "CU": "CU8", + "Version": "16.0.4075", + "KBList": "5029666" } ] } diff --git a/bin/dbatools-index.json b/bin/dbatools-index.json index b41c5ba5a0..4a4d464f53 100644 Binary files a/bin/dbatools-index.json and b/bin/dbatools-index.json differ diff --git a/bin/diagnosticquery/SQLServerDiagnosticQueries_2012.sql b/bin/diagnosticquery/SQLServerDiagnosticQueries_2012.sql index 7a9ab8cd29..ab18adb975 100644 --- a/bin/diagnosticquery/SQLServerDiagnosticQueries_2012.sql +++ b/bin/diagnosticquery/SQLServerDiagnosticQueries_2012.sql @@ -1,7 +1,7 @@ -- SQL Server 2012 Diagnostic Information Queries -- Glenn Berry --- Last Modified: June 5, 2023 +-- Last Modified: September 1, 2023 -- https://glennsqlperformance.com/ -- https://sqlserverperformance.wordpress.com/ -- YouTube: https://bit.ly/2PkoAM1 @@ -1654,10 +1654,10 @@ ORDER BY [BufferCount] DESC OPTION (RECOMPILE); -- Get Schema names, Table names, object size, row counts, and compression status for clustered index or heap (Query 64) (Table Sizes) -SELECT DB_NAME(DB_ID()) AS [Database Name], SCHEMA_NAME(o.Schema_ID) AS [Schema Name], +SELECT DB_NAME(DB_ID()) AS [Database Name], SCHEMA_NAME(o.schema_id) AS [Schema Name], OBJECT_NAME(p.object_id) AS [Table Name], CAST(SUM(ps.reserved_page_count) * 8.0 / 1024 AS DECIMAL(19,2)) AS [Object Size (MB)], -SUM(p.Rows) AS [Row Count], +SUM(p.rows) AS [Row Count], p.data_compression_desc AS [Compression Type] FROM sys.objects AS o WITH (NOLOCK) INNER JOIN sys.partitions AS p WITH (NOLOCK) @@ -1667,8 +1667,8 @@ ON p.object_id = ps.object_id WHERE ps.index_id < 2 -- ignore the partitions from the non-clustered indexes if any AND p.index_id < 2 -- ignore the partitions from the non-clustered indexes if any AND o.type_desc = N'USER_TABLE' -GROUP BY SCHEMA_NAME(o.Schema_ID), p.object_id, ps.reserved_page_count, p.data_compression_desc -ORDER BY SUM(ps.reserved_page_count) DESC, SUM(p.Rows) DESC OPTION (RECOMPILE); +GROUP BY SCHEMA_NAME(o.schema_id), p.object_id, ps.reserved_page_count, p.data_compression_desc +ORDER BY SUM(ps.reserved_page_count) DESC, SUM(p.rows) DESC OPTION (RECOMPILE); ------ -- Gives you an idea of table sizes, and possible data compression opportunities diff --git a/bin/diagnosticquery/SQLServerDiagnosticQueries_2014.sql b/bin/diagnosticquery/SQLServerDiagnosticQueries_2014.sql index 084d13a03c..7329110312 100644 --- a/bin/diagnosticquery/SQLServerDiagnosticQueries_2014.sql +++ b/bin/diagnosticquery/SQLServerDiagnosticQueries_2014.sql @@ -1,7 +1,7 @@ -- SQL Server 2014 Diagnostic Information Queries -- Glenn Berry --- Last Modified: June 5, 2023 +-- Last Modified: September 1, 2023 -- https://glennsqlperformance.com/ -- https://sqlserverperformance.wordpress.com/ -- YouTube: https://bit.ly/2PkoAM1 @@ -1704,10 +1704,10 @@ ORDER BY [BufferCount] DESC OPTION (RECOMPILE); -- Get Schema names, Table names, object size, row counts, and compression status for clustered index or heap (Query 66) (Table Sizes) -SELECT DB_NAME(DB_ID()) AS [Database Name], SCHEMA_NAME(o.Schema_ID) AS [Schema Name], +SELECT DB_NAME(DB_ID()) AS [Database Name], SCHEMA_NAME(o.schema_id) AS [Schema Name], OBJECT_NAME(p.object_id) AS [Table Name], CAST(SUM(ps.reserved_page_count) * 8.0 / 1024 AS DECIMAL(19,2)) AS [Object Size (MB)], -SUM(p.Rows) AS [Row Count], +SUM(p.rows) AS [Row Count], p.data_compression_desc AS [Compression Type] FROM sys.objects AS o WITH (NOLOCK) INNER JOIN sys.partitions AS p WITH (NOLOCK) @@ -1717,8 +1717,8 @@ ON p.object_id = ps.object_id WHERE ps.index_id < 2 -- ignore the partitions from the non-clustered indexes if any AND p.index_id < 2 -- ignore the partitions from the non-clustered indexes if any AND o.type_desc = N'USER_TABLE' -GROUP BY SCHEMA_NAME(o.Schema_ID), p.object_id, ps.reserved_page_count, p.data_compression_desc -ORDER BY SUM(ps.reserved_page_count) DESC, SUM(p.Rows) DESC OPTION (RECOMPILE); +GROUP BY SCHEMA_NAME(o.schema_id), p.object_id, ps.reserved_page_count, p.data_compression_desc +ORDER BY SUM(ps.reserved_page_count) DESC, SUM(p.rows) DESC OPTION (RECOMPILE); ------ -- Gives you an idea of table sizes, and possible data compression opportunities diff --git a/bin/diagnosticquery/SQLServerDiagnosticQueries_2016.sql b/bin/diagnosticquery/SQLServerDiagnosticQueries_2016.sql index 76ccae4603..898c43ee30 100644 --- a/bin/diagnosticquery/SQLServerDiagnosticQueries_2016.sql +++ b/bin/diagnosticquery/SQLServerDiagnosticQueries_2016.sql @@ -1,7 +1,7 @@ -- SQL Server 2016 Diagnostic Information Queries -- Glenn Berry --- Last Modified: June 5, 2023 +-- Last Modified: September 1, 2023 -- https://glennsqlperformance.com/ -- https://sqlserverperformance.wordpress.com/ -- YouTube: https://bit.ly/2PkoAM1 @@ -1770,10 +1770,10 @@ ORDER BY [BufferCount] DESC OPTION (RECOMPILE); -- Get Schema names, Table names, object size, row counts, and compression status for clustered index or heap (Query 67) (Table Sizes) -SELECT DB_NAME(DB_ID()) AS [Database Name], SCHEMA_NAME(o.Schema_ID) AS [Schema Name], +SELECT DB_NAME(DB_ID()) AS [Database Name], SCHEMA_NAME(o.schema_id) AS [Schema Name], OBJECT_NAME(p.object_id) AS [Table Name], CAST(SUM(ps.reserved_page_count) * 8.0 / 1024 AS DECIMAL(19,2)) AS [Object Size (MB)], -SUM(p.Rows) AS [Row Count], +SUM(p.rows) AS [Row Count], p.data_compression_desc AS [Compression Type] FROM sys.objects AS o WITH (NOLOCK) INNER JOIN sys.partitions AS p WITH (NOLOCK) @@ -1783,8 +1783,8 @@ ON p.object_id = ps.object_id WHERE ps.index_id < 2 -- ignore the partitions from the non-clustered indexes if any AND p.index_id < 2 -- ignore the partitions from the non-clustered indexes if any AND o.type_desc = N'USER_TABLE' -GROUP BY SCHEMA_NAME(o.Schema_ID), p.object_id, ps.reserved_page_count, p.data_compression_desc -ORDER BY SUM(ps.reserved_page_count) DESC, SUM(p.Rows) DESC OPTION (RECOMPILE); +GROUP BY SCHEMA_NAME(o.schema_id), p.object_id, ps.reserved_page_count, p.data_compression_desc +ORDER BY SUM(ps.reserved_page_count) DESC, SUM(p.rows) DESC OPTION (RECOMPILE); ------ -- Gives you an idea of table sizes, and possible data compression opportunities diff --git a/bin/diagnosticquery/SQLServerDiagnosticQueries_2016SP2.sql b/bin/diagnosticquery/SQLServerDiagnosticQueries_2016SP2.sql index 66377bdae2..a18b0cd4a0 100644 --- a/bin/diagnosticquery/SQLServerDiagnosticQueries_2016SP2.sql +++ b/bin/diagnosticquery/SQLServerDiagnosticQueries_2016SP2.sql @@ -1,7 +1,7 @@ -- SQL Server 2016 SP2 Diagnostic Information Queries -- Glenn Berry --- Last Modified: June 5, 2023 +-- Last Modified: September 1, 2023 -- https://glennsqlperformance.com/ -- https://sqlserverperformance.wordpress.com/ -- YouTube: https://bit.ly/2PkoAM1 @@ -1754,10 +1754,10 @@ ORDER BY cp.usecounts DESC OPTION (RECOMPILE); -- Breaks down buffers used by current database by object (table, index) in the buffer cache (Query 69) (Buffer Usage) -- Note: This query could take some time on a busy instance -SELECT fg.name AS [Filegroup Name], SCHEMA_NAME(o.Schema_ID) AS [Schema Name], +SELECT fg.name AS [Filegroup Name], SCHEMA_NAME(o.schema_id) AS [Schema Name], OBJECT_NAME(p.[object_id]) AS [Object Name], p.index_id, CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)], -COUNT(*) AS [BufferCount], p.[Rows] AS [Row Count], +COUNT(*) AS [BufferCount], p.[rows] AS [Row Count], p.data_compression_desc AS [Compression Type] FROM sys.allocation_units AS a WITH (NOLOCK) INNER JOIN sys.dm_os_buffer_descriptors AS b WITH (NOLOCK) @@ -1775,8 +1775,8 @@ AND p.[object_id] > 100 AND OBJECT_NAME(p.[object_id]) NOT LIKE N'plan_%' AND OBJECT_NAME(p.[object_id]) NOT LIKE N'sys%' AND OBJECT_NAME(p.[object_id]) NOT LIKE N'xml_index_nodes%' -GROUP BY fg.name, o.Schema_ID, p.[object_id], p.index_id, - p.data_compression_desc, p.[Rows] +GROUP BY fg.name, o.schema_id, p.[object_id], p.index_id, + p.data_compression_desc, p.[rows] ORDER BY [BufferCount] DESC OPTION (RECOMPILE); ------ @@ -1785,10 +1785,10 @@ ORDER BY [BufferCount] DESC OPTION (RECOMPILE); -- Get Schema names, Table names, object size, row counts, and compression status for clustered index or heap (Query 70) (Table Sizes) -SELECT DB_NAME(DB_ID()) AS [Database Name], SCHEMA_NAME(o.Schema_ID) AS [Schema Name], +SELECT DB_NAME(DB_ID()) AS [Database Name], SCHEMA_NAME(o.schema_id) AS [Schema Name], OBJECT_NAME(p.object_id) AS [Table Name], CAST(SUM(ps.reserved_page_count) * 8.0 / 1024 AS DECIMAL(19,2)) AS [Object Size (MB)], -SUM(p.Rows) AS [Row Count], +SUM(p.rows) AS [Row Count], p.data_compression_desc AS [Compression Type] FROM sys.objects AS o WITH (NOLOCK) INNER JOIN sys.partitions AS p WITH (NOLOCK) @@ -1798,8 +1798,8 @@ ON p.object_id = ps.object_id WHERE ps.index_id < 2 -- ignore the partitions from the non-clustered indexes if any AND p.index_id < 2 -- ignore the partitions from the non-clustered indexes if any AND o.type_desc = N'USER_TABLE' -GROUP BY SCHEMA_NAME(o.Schema_ID), p.object_id, ps.reserved_page_count, p.data_compression_desc -ORDER BY SUM(ps.reserved_page_count) DESC, SUM(p.Rows) DESC OPTION (RECOMPILE); +GROUP BY SCHEMA_NAME(o.schema_id), p.object_id, ps.reserved_page_count, p.data_compression_desc +ORDER BY SUM(ps.reserved_page_count) DESC, SUM(p.rows) DESC OPTION (RECOMPILE); ------ -- Gives you an idea of table sizes, and possible data compression opportunities @@ -1830,7 +1830,7 @@ ORDER BY OBJECT_NAME(t.[object_id]), p.index_id OPTION (RECOMPILE); -- When were Statistics last updated on all indexes? (Query 72) (Statistics Update) -SELECT SCHEMA_NAME(o.Schema_ID) + N'.' + o.[NAME] AS [Object Name], o.[type_desc] AS [Object Type], +SELECT SCHEMA_NAME(o.schema_id) + N'.' + o.[name] AS [Object Name], o.[type_desc] AS [Object Type], i.[name] AS [Index Name], STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date], s.auto_created, s.no_recompute, s.user_created, s.is_incremental, s.is_temporary, sp.persisted_sample_percent, @@ -1884,7 +1884,7 @@ ORDER BY sp.modification_counter DESC, o.name OPTION (RECOMPILE); -- Get fragmentation info for all indexes above a certain size in the current database (Query 74) (Index Fragmentation) -- Note: This query could take some time on a very large database SELECT DB_NAME(ps.database_id) AS [Database Name], SCHEMA_NAME(o.[schema_id]) AS [Schema Name], -OBJECT_NAME(ps.OBJECT_ID) AS [Object Name], i.[name] AS [Index Name], ps.index_id, ps.index_type_desc, +OBJECT_NAME(ps.object_id) AS [Object Name], i.[name] AS [Index Name], ps.index_id, ps.index_type_desc, CAST(ps.avg_fragmentation_in_percent AS DECIMAL (15,3)) AS [Avg Fragmentation in Pct], ps.fragment_count, ps.page_count, i.fill_factor, i.has_filter, i.filter_definition, i.[allow_page_locks] FROM sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS ps diff --git a/bin/diagnosticquery/SQLServerDiagnosticQueries_2017.sql b/bin/diagnosticquery/SQLServerDiagnosticQueries_2017.sql index bbfabde767..2c9a48b957 100644 --- a/bin/diagnosticquery/SQLServerDiagnosticQueries_2017.sql +++ b/bin/diagnosticquery/SQLServerDiagnosticQueries_2017.sql @@ -1,7 +1,7 @@ -- SQL Server 2017 Diagnostic Information Queries -- Glenn Berry --- Last Modified: June 5, 2023 +-- Last Modified: September 1, 2023 -- https://glennsqlperformance.com/ -- https://sqlserverperformance.wordpress.com/ -- YouTube: https://bit.ly/2PkoAM1 @@ -1822,10 +1822,10 @@ ORDER BY [BufferCount] DESC OPTION (RECOMPILE); -- Get Schema names, Table names, object size, row counts, and compression status for clustered index or heap (Query 71) (Table Sizes) -SELECT DB_NAME(DB_ID()) AS [Database Name], SCHEMA_NAME(o.Schema_ID) AS [Schema Name], +SELECT DB_NAME(DB_ID()) AS [Database Name], SCHEMA_NAME(o.schema_id) AS [Schema Name], OBJECT_NAME(p.object_id) AS [Table Name], CAST(SUM(ps.reserved_page_count) * 8.0 / 1024 AS DECIMAL(19,2)) AS [Object Size (MB)], -SUM(p.Rows) AS [Row Count], +SUM(p.rows) AS [Row Count], p.data_compression_desc AS [Compression Type] FROM sys.objects AS o WITH (NOLOCK) INNER JOIN sys.partitions AS p WITH (NOLOCK) @@ -1835,8 +1835,8 @@ ON p.object_id = ps.object_id WHERE ps.index_id < 2 -- ignore the partitions from the non-clustered indexes if any AND p.index_id < 2 -- ignore the partitions from the non-clustered indexes if any AND o.type_desc = N'USER_TABLE' -GROUP BY SCHEMA_NAME(o.Schema_ID), p.object_id, ps.reserved_page_count, p.data_compression_desc -ORDER BY SUM(ps.reserved_page_count) DESC, SUM(p.Rows) DESC OPTION (RECOMPILE); +GROUP BY SCHEMA_NAME(o.schema_id), p.object_id, ps.reserved_page_count, p.data_compression_desc +ORDER BY SUM(ps.reserved_page_count) DESC, SUM(p.rows) DESC OPTION (RECOMPILE); ------ -- Gives you an idea of table sizes, and possible data compression opportunities diff --git a/bin/diagnosticquery/SQLServerDiagnosticQueries_2019.sql b/bin/diagnosticquery/SQLServerDiagnosticQueries_2019.sql index 3516a94b71..2d3b393297 100644 --- a/bin/diagnosticquery/SQLServerDiagnosticQueries_2019.sql +++ b/bin/diagnosticquery/SQLServerDiagnosticQueries_2019.sql @@ -1,7 +1,7 @@ -- SQL Server 2019 Diagnostic Information Queries -- Glenn Berry --- Last Modified: June 5, 2023 +-- Last Modified: September 1, 2023 -- https://glennsqlperformance.com/ -- https://sqlserverperformance.wordpress.com/ -- YouTube: https://bit.ly/2PkoAM1 @@ -92,8 +92,9 @@ SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version In -- 15.0.4261.1 CU18 9/28/2022 https://support.microsoft.com/en-us/topic/kb5017593-cumulative-update-18-for-sql-server-2019-5fa00c36-edeb-446c-94e3-c4882b7526bc -- 15.0.4280.7 CU18 GDR 2/14/2023 https://support.microsoft.com/en-us/topic/kb5021124-description-of-the-security-update-for-sql-server-2019-cu18-february-14-2023-cfb75a0a-33dc-4e05-8645-4cf16fcec049 -- 15.0.4298.1 CU19 2/16/2023 https://support.microsoft.com/en-us/topic/kb5023049-cumulative-update-19-for-sql-server-2019-b63d7163-e2e7-46f7-b50a-c3d1f2913219 --- 14.0.4312.2 CU20 4/13/2023 https://support.microsoft.com/en-us/topic/kb5024276-cumulative-update-20-for-sql-server-2019-4b282be9-b559-46ac-9b6a-badbd44785d2 - +-- 15.0.4312.2 CU20 4/13/2023 https://support.microsoft.com/en-us/topic/kb5024276-cumulative-update-20-for-sql-server-2019-4b282be9-b559-46ac-9b6a-badbd44785d2 +-- 15.0.4316.3 CU21 6/15/2022 https://learn.microsoft.com/en-us/troubleshoot/sql/releases/sqlserver-2019/cumulativeupdate21 +-- 15.0.4322.2 CU22 8/14/2023 https://learn.microsoft.com/en-us/troubleshoot/sql/releases/sqlserver-2019/cumulativeupdate22 -- How to determine the version, edition and update level of SQL Server and its components -- https://bit.ly/2oAjKgW @@ -226,6 +227,11 @@ DBCC TRACESTATUS (-1); -- TF 7745 - Prevents Query Store data from being written to disk in case of a failover or shutdown command -- https://bit.ly/2GU69Km +-- TF 8121 - Fixes a system-wide low memory issue that occurs when SQL Server commits memory above the maximum server memory under the memory model with the Lock Pages In Memory (added in CU15) +-- https://learn.microsoft.com/en-US/troubleshoot/sql/releases/sqlserver-2019/cumulativeupdate15#bkmk_14421838 + + + -- DBCC TRACEON - Trace Flags (Transact-SQL) -- https://bit.ly/2FuSvPg @@ -1109,6 +1115,7 @@ AS (SELECT wait_type, wait_time_ms/ 1000.0 AS [WaitS], N'MEMORY_ALLOCATION_EXT', N'ONDEMAND_TASK_QUEUE', N'PARALLEL_REDO_DRAIN_WORKER', N'PARALLEL_REDO_LOG_CACHE', N'PARALLEL_REDO_TRAN_LIST', N'PARALLEL_REDO_WORKER_SYNC', N'PARALLEL_REDO_WORKER_WAIT_WORK', + N'PREEMPTIVE_COM_GETDATA', N'PREEMPTIVE_COM_QUERYINTERFACE', N'PREEMPTIVE_HADR_LEASE_MECHANISM', N'PREEMPTIVE_SP_SERVER_DIAGNOSTICS', N'PREEMPTIVE_OS_LIBRARYOPS', N'PREEMPTIVE_OS_COMOPS', N'PREEMPTIVE_OS_CRYPTOPS', N'PREEMPTIVE_OS_PIPEOPS', N'PREEMPTIVE_OS_AUTHENTICATIONOPS', diff --git a/bin/diagnosticquery/SQLServerDiagnosticQueries_2022.sql b/bin/diagnosticquery/SQLServerDiagnosticQueries_2022.sql index 74a0843cdf..98a3e7481d 100644 --- a/bin/diagnosticquery/SQLServerDiagnosticQueries_2022.sql +++ b/bin/diagnosticquery/SQLServerDiagnosticQueries_2022.sql @@ -1,7 +1,7 @@ -- SQL Server 2022 Diagnostic Information Queries -- Glenn Berry --- Last Modified: June 5, 2023 +-- Last Modified: September 19, 2023 -- https://glennsqlperformance.com/ -- https://sqlserverperformance.wordpress.com/ -- YouTube: https://bit.ly/2PkoAM1 @@ -68,6 +68,10 @@ SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version In -- 16.0.4015.1 CU2 3/15/2023 https://learn.microsoft.com/en-US/troubleshoot/sql/releases/sqlserver-2022/cumulativeupdate2 -- 16.0.4025.1 CU3 4/13/2023 https://support.microsoft.com/en-us/topic/kb5024396-cumulative-update-3-for-sql-server-2022-db3fcc1d-c788-4180-8afe-0a742cd77026 -- 16.0.4035.4 CU4 5/11/2023 https://support.microsoft.com/en-us/topic/kb5026717-cumulative-update-4-for-sql-server-2022-48798a25-5c8c-4f3e-b608-7484dd2be091 +-- 16.0.4045.3 CU5 6/15/2023 https://learn.microsoft.com/en-us/troubleshoot/sql/releases/sqlserver-2022/cumulativeupdate5 +-- 16.0.4055.4 CU6 7/13/2023 https://learn.microsoft.com/en-us/troubleshoot/sql/releases/sqlserver-2022/cumulativeupdate6 +-- 16.0.4065.3 CU7 8/10/2023 https://learn.microsoft.com/en-us/troubleshoot/sql/releases/sqlserver-2022/cumulativeupdate7 +-- 16.0.4075.1 CU8 9/14/2023 https://learn.microsoft.com/en-us/troubleshoot/sql/releases/sqlserver-2022/cumulativeupdate8 -- What's new in SQL Server 2022 (16.x) -- https://bit.ly/3MJEjR1 @@ -1968,10 +1972,10 @@ ORDER BY [BufferCount] DESC OPTION (RECOMPILE); -- Get Schema names, Table names, object size, row counts, and compression status for clustered index or heap (Query 75) (Table Sizes) -SELECT DB_NAME(DB_ID()) AS [Database Name], SCHEMA_NAME(o.Schema_ID) AS [Schema Name], +SELECT DB_NAME(DB_ID()) AS [Database Name], SCHEMA_NAME(o.schema_id) AS [Schema Name], OBJECT_NAME(p.object_id) AS [Table Name], CAST(SUM(ps.reserved_page_count) * 8.0 / 1024 AS DECIMAL(19,2)) AS [Object Size (MB)], -SUM(p.Rows) AS [Row Count], +SUM(p.rows) AS [Row Count], p.data_compression_desc AS [Compression Type] FROM sys.objects AS o WITH (NOLOCK) INNER JOIN sys.partitions AS p WITH (NOLOCK) @@ -1981,8 +1985,8 @@ ON p.object_id = ps.object_id WHERE ps.index_id < 2 -- ignore the partitions from the non-clustered indexes if any AND p.index_id < 2 -- ignore the partitions from the non-clustered indexes if any AND o.type_desc = N'USER_TABLE' -GROUP BY SCHEMA_NAME(o.Schema_ID), p.object_id, ps.reserved_page_count, p.data_compression_desc -ORDER BY SUM(ps.reserved_page_count) DESC, SUM(p.Rows) DESC OPTION (RECOMPILE); +GROUP BY SCHEMA_NAME(o.schema_id), p.object_id, ps.reserved_page_count, p.data_compression_desc +ORDER BY SUM(ps.reserved_page_count) DESC, SUM(p.rows) DESC OPTION (RECOMPILE); ------ -- Gives you an idea of table sizes, and possible data compression opportunities diff --git a/private/functions/Convert-DbaIndexToTable.ps1 b/private/functions/Convert-DbaIndexToTable.ps1 index ed729236dc..ccde0c4062 100644 --- a/private/functions/Convert-DbaIndexToTable.ps1 +++ b/private/functions/Convert-DbaIndexToTable.ps1 @@ -76,6 +76,10 @@ function Convert-DbaIndexToTable { { $_ -in "bigint", "date", "datetime", "datetime2", "smallint", "time", "tinyint" } { $columnStatements += "[$($columnObject.Name)] [$dataType]" } + { $_ -like "*varcharmax" } { + $columnStatements += "[$($columnObject.Name)] [$($dataType.Replace('max',''))](max)" + break + } { $_ -like "*char*" } { $columnStatements += "[$($columnObject.Name)] [$dataType]($length)" } diff --git a/private/functions/Get-DecryptedObject.ps1 b/private/functions/Get-DecryptedObject.ps1 index 4f7a44553b..17ee3242de 100644 --- a/private/functions/Get-DecryptedObject.ps1 +++ b/private/functions/Get-DecryptedObject.ps1 @@ -49,7 +49,7 @@ function Get-DecryptedObject { return $serviceKey } } catch { - Stop-Function -Message "Can't unprotect registry data on $sourceName. Do you have administrative access to the Windows registry on $sourceName? Otherwise, we're out of ideas." -Target $sourceName + Stop-Function -Message "Can't unprotect registry data on $sourceName. Do you have administrative access to the Windows registry on $($sourceName)? Otherwise, we're out of ideas." -Target $sourceName return } @@ -59,7 +59,7 @@ function Get-DecryptedObject { if (($serviceKey.Length -ne 16) -and ($serviceKey.Length -ne 32)) { Write-Message -Level Verbose -Message "ServiceKey found: $serviceKey.Length" - Stop-Function -Message "Unknown key size. Do you have administrative access to the Windows registry on $sourceName? Otherwise, we're out of ideas." -Target $sourceName + Stop-Function -Message "Unknown key size. Do you have administrative access to the Windows registry on $($sourceName)? Otherwise, we're out of ideas." -Target $sourceName return } @@ -208,4 +208,4 @@ function Get-DecryptedObject { ProviderName = $ProviderName } } -} \ No newline at end of file +} diff --git a/private/functions/New-DbaLogShippingPrimaryDatabase.ps1 b/private/functions/New-DbaLogShippingPrimaryDatabase.ps1 index cbfe91ee63..96fda06845 100644 --- a/private/functions/New-DbaLogShippingPrimaryDatabase.ps1 +++ b/private/functions/New-DbaLogShippingPrimaryDatabase.ps1 @@ -134,7 +134,7 @@ function New-DbaLogShippingPrimaryDatabase { Stop-Function -Message "The backup share path $BackupShare should be formatted in the form \\server\share." -Target $SqlInstance return } else { - if (-not ((Test-DbaPath $BackupShare -SqlInstance $server) -and ((Get-Item $BackupShare).PSProvider.Name -eq 'FileSystem'))) { + if (-not ((Test-DbaPath -Path $BackupShare -SqlInstance $server) -and ((Get-Item $BackupShare).PSProvider.Name -eq 'FileSystem'))) { Stop-Function -Message "The backup share path $BackupShare is not valid or can't be reached." -Target $SqlInstance return } diff --git a/private/functions/New-DbaLogShippingSecondaryPrimary.ps1 b/private/functions/New-DbaLogShippingSecondaryPrimary.ps1 index 6a586199ac..a89ac22dae 100644 --- a/private/functions/New-DbaLogShippingSecondaryPrimary.ps1 +++ b/private/functions/New-DbaLogShippingSecondaryPrimary.ps1 @@ -132,7 +132,7 @@ function New-DbaLogShippingSecondaryPrimary { Stop-Function -Message "The backup destination path should be formatted in the form \\server\share." -Target $SqlInstance return } else { - if (-not ((Test-DbaPath $BackupDestinationDirectory -SqlInstance $ServerSecondary) -and ((Get-Item $BackupDestinationDirectory).PSProvider.Name -eq 'FileSystem'))) { + if (-not ((Test-DbaPath -Path $BackupDestinationDirectory -SqlInstance $ServerSecondary) -and ((Get-Item $BackupDestinationDirectory).PSProvider.Name -eq 'FileSystem'))) { Stop-Function -Message "The backup destination path is not valid or can't be reached." -Target $SqlInstance return } diff --git a/public/Add-DbaAgDatabase.ps1 b/public/Add-DbaAgDatabase.ps1 index 5064ef4186..85eaf5ed1b 100644 --- a/public/Add-DbaAgDatabase.ps1 +++ b/public/Add-DbaAgDatabase.ps1 @@ -531,4 +531,4 @@ function Add-DbaAgDatabase { } Write-Progress @progress -Completed } -} +} \ No newline at end of file diff --git a/public/Add-DbaAgReplica.ps1 b/public/Add-DbaAgReplica.ps1 index 13e2d5453c..58eb91fc94 100644 --- a/public/Add-DbaAgReplica.ps1 +++ b/public/Add-DbaAgReplica.ps1 @@ -390,4 +390,4 @@ function Add-DbaAgReplica { } } } -} +} \ No newline at end of file diff --git a/public/Add-DbaDbMirrorMonitor.ps1 b/public/Add-DbaDbMirrorMonitor.ps1 index 7732851749..e7d510ad67 100644 --- a/public/Add-DbaDbMirrorMonitor.ps1 +++ b/public/Add-DbaDbMirrorMonitor.ps1 @@ -63,7 +63,7 @@ function Add-DbaDbMirrorMonitor { if ($Pscmdlet.ShouldProcess($instance, "add mirror monitoring")) { try { $server.Query("msdb.dbo.sp_dbmmonitoraddmonitoring") - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Add-DbaDbRoleMember.ps1 b/public/Add-DbaDbRoleMember.ps1 index 40626f318e..b4c9fb3211 100644 --- a/public/Add-DbaDbRoleMember.ps1 +++ b/public/Add-DbaDbRoleMember.ps1 @@ -107,15 +107,15 @@ function Add-DbaDbRoleMember { switch ($inputType) { 'Dataplat.Dbatools.Parameter.DbaInstanceParameter' { Write-Message -Level Verbose -Message "Processing DbaInstanceParameter through InputObject" - $dbRoles = Get-DbaDBRole -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -Role $Role + $dbRoles = Get-DbaDbRole -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -Role $Role } 'Microsoft.SqlServer.Management.Smo.Server' { Write-Message -Level Verbose -Message "Processing Server through InputObject" - $dbRoles = Get-DbaDBRole -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -Role $Role + $dbRoles = Get-DbaDbRole -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -Role $Role } 'Microsoft.SqlServer.Management.Smo.Database' { Write-Message -Level Verbose -Message "Processing Database through InputObject" - $dbRoles = $input | Get-DbaDBRole -Role $Role + $dbRoles = $input | Get-DbaDbRole -Role $Role } 'Microsoft.SqlServer.Management.Smo.DatabaseRole' { Write-Message -Level Verbose -Message "Processing DatabaseRole through InputObject" @@ -154,4 +154,4 @@ function Add-DbaDbRoleMember { } } } -} +} \ No newline at end of file diff --git a/public/Add-DbaExtendedProperty.ps1 b/public/Add-DbaExtendedProperty.ps1 index 6d62d452cf..66806cf48f 100644 --- a/public/Add-DbaExtendedProperty.ps1 +++ b/public/Add-DbaExtendedProperty.ps1 @@ -156,4 +156,4 @@ function Add-DbaExtendedProperty { } } } -} +} \ No newline at end of file diff --git a/public/Add-DbaReplArticle.ps1 b/public/Add-DbaReplArticle.ps1 new file mode 100644 index 0000000000..3fb0ac4ac6 --- /dev/null +++ b/public/Add-DbaReplArticle.ps1 @@ -0,0 +1,196 @@ +function Add-DbaReplArticle { + <# + .SYNOPSIS + Add an article configuration to a publication in a database on the SQL Server instance(s). + + .DESCRIPTION + Add an article configuration to a publication in a database on the SQL Server instance(s). + + .PARAMETER SqlInstance + The SQL Server instance(s) for the publication. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER Database + The publication database to apply the article configuration to be replicated. + + .PARAMETER Publication + The name of the publication. + + .PARAMETER Schema + Schema where the article to be added is found. + Default is dbo. + + .PARAMETER Name + The name of the object to add as an article. + + .PARAMETER Filter + Sets the where clause used to filter the article horizontally, e.g., DiscontinuedDate IS NULL + E.g. City = 'Seattle' + + .PARAMETER CreationScriptOptions + Options for the creation script. + Use New-DbaReplCreationScriptOptions to create this object. + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .PARAMETER WhatIf + If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. + + .PARAMETER Confirm + If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. + + .NOTES + Tags: repl, Replication + Author: Jess Pomfret (@jpomfret), jesspomfret.com + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + https://learn.microsoft.com/en-us/sql/relational-databases/replication/publish/define-an-article?view=sql-server-ver16#RMOProcedure + + .LINK + https://dbatools.io/Add-DbaReplArticle + + .EXAMPLE + PS C:\> Add-DbaReplArticle -SqlInstance mssql1 -Database Northwind -Publication PubFromPosh -Name TableToRepl + + Adds the TableToRepl table to the PubFromPosh publication from mssql1.Northwind + + .EXAMPLE + PS C:\> $article = @{ + SqlInstance = "mssql1" + Database = "pubs" + Publication = "testPub" + Name = "publishers" + Filter = "city = 'seattle'" + } + PS C:\> Add-DbaReplArticle @article -EnableException + + Adds the publishers table to the TestPub publication from mssql1.Pubs with a horizontal filter of only rows where city = 'seattle. + + .EXAMPLE + PS C:\> $cso = New-DbaReplCreationScriptOptions -Options NonClusteredIndexes, Statistics + PS C:\> $article = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + Publication = 'testPub' + Name = 'stores' + CreationScriptOptions = $cso + } + PS C:\> Add-DbaReplArticle @article -EnableException + + Adds the stores table to the testPub publication from mssql1.pubs with the NonClusteredIndexes and Statistics options set + includes default options. + #> + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param ( + [Parameter(Mandatory, ValueFromPipeline)] + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [parameter(Mandatory)] + [string]$Database, + [Parameter(Mandatory)] + [string]$Publication, + [string]$Schema = 'dbo', + [Parameter(Mandatory)] + [string]$Name, + [string]$Filter, + [PSObject]$CreationScriptOptions, + [switch]$EnableException + ) + process { + + # Check that $CreationScriptOptions is a valid object + if ($CreationScriptOptions -and ($CreationScriptOptions -isnot [Microsoft.SqlServer.Replication.CreationScriptOptions])) { + Stop-Function -Message "CreationScriptOptions should be the right type. Use New-DbaReplCreationScriptOptions to create the object" -ErrorRecord $_ -Target $instance -Continue + } + + if ($Filter -like 'WHERE*') { + Stop-Function -Message "Filter should not include the word 'WHERE'" -ErrorRecord $_ -Target $instance -Continue + } + + foreach ($instance in $SqlInstance) { + try { + $replServer = Get-DbaReplServer -SqlInstance $instance -SqlCredential $SqlCredential -EnableException:$EnableException + } catch { + Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue + } + Write-Message -Level Verbose -Message "Adding article $Name to publication $Publication on $instance" + + try { + if ($PSCmdlet.ShouldProcess($instance, "Get the publication details for $Publication")) { + + $pub = Get-DbaReplPublication -SqlInstance $instance -SqlCredential $SqlCredential -Name $Publication -EnableException:$EnableException + if (-not $pub) { + Stop-Function -Message "Publication $Publication does not exist on $instance" -ErrorRecord $_ -Target $instance -Continue + } + } + } catch { + Stop-Function -Message "Unable to get publication $Publication on $instance" -ErrorRecord $_ -Target $instance -Continue + } + + try { + if ($PSCmdlet.ShouldProcess($instance, "Create an article object for $Publication which is a $($pub.Type) publication")) { + + $articleOptions = New-Object Microsoft.SqlServer.Replication.ArticleOptions + + if ($pub.Type -in ('Transactional', 'Snapshot')) { + $article = New-Object Microsoft.SqlServer.Replication.TransArticle + $article.Type = $ArticleOptions::LogBased + } elseif ($pub.Type -eq 'Merge') { + $article = New-Object Microsoft.SqlServer.Replication.MergeArticle + $article.Type = $ArticleOptions::TableBased + } + + $article.ConnectionContext = $replServer.ConnectionContext + $article.Name = $Name + $article.DatabaseName = $Database + $article.SourceObjectName = $Name + $article.SourceObjectOwner = $Schema + $article.PublicationName = $Publication + } + } catch { + Stop-Function -Message "Unable to create article object for $Name to add to $Publication on $instance" -ErrorRecord $_ -Target $instance -Continue + } + + try { + if ($CreationScriptOptions) { + if ($PSCmdlet.ShouldProcess($instance, "Add creation options for article: $Name")) { + $article.SchemaOption = $CreationScriptOptions + } + } + + if ($Filter) { + if ($PSCmdlet.ShouldProcess($instance, "Add filter for article: $Name")) { + $article.FilterClause = $Filter + } + } + + if ($PSCmdlet.ShouldProcess($instance, "Create article: $Name")) { + if (-not ($article.IsExistingObject)) { + $article.Create() + } else { + Stop-Function -Message "Article already exists in $Publication on $instance" -ErrorRecord $_ -Target $instance -Continue + } + + if ($pub.Type -in ('Transactional', 'Snapshot')) { + $pub.RefreshSubscriptions() + } + } + } catch { + Stop-Function -Message "Unable to add article $Name to $Publication on $instance" -ErrorRecord $_ -Target $instance -Continue + } + Get-DbaReplArticle -SqlInstance $instance -SqlCredential $SqlCredential -Publication $Publication -Name $Name -EnableException:$EnableException + } + } +} \ No newline at end of file diff --git a/public/Add-DbaServerRoleMember.ps1 b/public/Add-DbaServerRoleMember.ps1 index f160be6e32..09caf3c5b4 100644 --- a/public/Add-DbaServerRoleMember.ps1 +++ b/public/Add-DbaServerRoleMember.ps1 @@ -195,4 +195,4 @@ function Add-DbaServerRoleMember { } } } -} +} \ No newline at end of file diff --git a/public/Backup-DbaDbCertificate.ps1 b/public/Backup-DbaDbCertificate.ps1 index 94360b6d39..a70bf88272 100644 --- a/public/Backup-DbaDbCertificate.ps1 +++ b/public/Backup-DbaDbCertificate.ps1 @@ -211,7 +211,7 @@ function Backup-DbaDbCertificate { # Sleep for a second to avoid another export in the same second Start-Sleep -Seconds 1 - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Connect-DbaInstance.ps1 b/public/Connect-DbaInstance.ps1 index b343494038..01b9d42aeb 100644 --- a/public/Connect-DbaInstance.ps1 +++ b/public/Connect-DbaInstance.ps1 @@ -1101,4 +1101,4 @@ function Connect-DbaInstance { Write-Message -Level Debug -Message "We are finished with this instance" } } -} +} \ No newline at end of file diff --git a/public/Copy-DbaAgentAlert.ps1 b/public/Copy-DbaAgentAlert.ps1 index c8c58568df..00a745e0f7 100644 --- a/public/Copy-DbaAgentAlert.ps1 +++ b/public/Copy-DbaAgentAlert.ps1 @@ -116,7 +116,7 @@ function Copy-DbaAgentAlert { if ($IncludeDefaults -eq $true) { if ($PSCmdlet.ShouldProcess($destinstance, "Creating Alert Defaults")) { - $copyAgentAlertStatus = [pscustomobject]@{ + $copyAgentAlertStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = "Alert Defaults" @@ -137,7 +137,7 @@ function Copy-DbaAgentAlert { } catch { $copyAgentAlertStatus.Status = "Failed" $copyAgentAlertStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject - Write-Message -Level Verbose -Message "Issue creating alert defaults on $destinstance | $PSitem" + Write-Message -Level Verbose -Message "Issue creating alert defaults on $destinstance | $PSItem" } } } @@ -146,7 +146,7 @@ function Copy-DbaAgentAlert { foreach ($serverAlert in $serverAlerts) { $alertName = $serverAlert.name - $copyAgentAlertStatus = [pscustomobject]@{ + $copyAgentAlertStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $alertName @@ -255,7 +255,7 @@ function Copy-DbaAgentAlert { # JobId = 00000000-0000-0000-0000-000 means the Alert does not execute/is attached to a SQL Agent Job. if ($serverAlert.JobId -ne '00000000-0000-0000-0000-000000000000') { - $copyAgentAlertStatus = [pscustomobject]@{ + $copyAgentAlertStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $alertName @@ -289,7 +289,7 @@ function Copy-DbaAgentAlert { if ($PSCmdlet.ShouldProcess($destinstance, "Moving Notifications $alertName")) { try { - $copyAgentAlertStatus = [pscustomobject]@{ + $copyAgentAlertStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $alertName diff --git a/public/Copy-DbaAgentJob.ps1 b/public/Copy-DbaAgentJob.ps1 index 8308f0cd28..d862f474a5 100644 --- a/public/Copy-DbaAgentJob.ps1 +++ b/public/Copy-DbaAgentJob.ps1 @@ -130,7 +130,7 @@ function Copy-DbaAgentJob { $jobId = $serverJob.JobId $sourceserver = $serverJob.Parent.Parent - $copyJobStatus = [pscustomobject]@{ + $copyJobStatus = [PSCustomObject]@{ SourceServer = $sourceserver.Name DestinationServer = $destServer.Name Name = $jobName diff --git a/public/Copy-DbaAgentJobCategory.ps1 b/public/Copy-DbaAgentJobCategory.ps1 index bfb8cd9310..0bf26aa2df 100644 --- a/public/Copy-DbaAgentJobCategory.ps1 +++ b/public/Copy-DbaAgentJobCategory.ps1 @@ -128,7 +128,7 @@ function Copy-DbaAgentJobCategory { foreach ($jobCategory in $serverJobCategories) { $categoryName = $jobCategory.Name - $copyJobCategoryStatus = [pscustomobject]@{ + $copyJobCategoryStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $categoryName @@ -206,7 +206,7 @@ function Copy-DbaAgentJobCategory { foreach ($operatorCategory in $serverOperatorCategories) { $categoryName = $operatorCategory.Name - $copyOperatorCategoryStatus = [pscustomobject]@{ + $copyOperatorCategoryStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Type = "Agent Operator Category" @@ -294,7 +294,7 @@ function Copy-DbaAgentJobCategory { foreach ($alertCategory in $serverAlertCategories) { $categoryName = $alertCategory.Name - $copyAlertCategoryStatus = [pscustomobject]@{ + $copyAlertCategoryStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Type = "Agent Alert Category" diff --git a/public/Copy-DbaAgentOperator.ps1 b/public/Copy-DbaAgentOperator.ps1 index 4137ff3001..2395b365d6 100644 --- a/public/Copy-DbaAgentOperator.ps1 +++ b/public/Copy-DbaAgentOperator.ps1 @@ -118,7 +118,7 @@ function Copy-DbaAgentOperator { foreach ($sOperator in $serverOperator) { $operatorName = $sOperator.Name - $copyOperatorStatus = [pscustomobject]@{ + $copyOperatorStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $operatorName diff --git a/public/Copy-DbaAgentProxy.ps1 b/public/Copy-DbaAgentProxy.ps1 index 1340e346f2..b999e2aa23 100644 --- a/public/Copy-DbaAgentProxy.ps1 +++ b/public/Copy-DbaAgentProxy.ps1 @@ -120,7 +120,7 @@ function Copy-DbaAgentProxy { foreach ($account in $serverProxyAccounts) { $proxyName = $account.Name - $copyAgentProxyAccountStatus = [pscustomobject]@{ + $copyAgentProxyAccountStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $null diff --git a/public/Copy-DbaAgentSchedule.ps1 b/public/Copy-DbaAgentSchedule.ps1 index 59a6a85e8f..408b33991d 100644 --- a/public/Copy-DbaAgentSchedule.ps1 +++ b/public/Copy-DbaAgentSchedule.ps1 @@ -128,7 +128,7 @@ function Copy-DbaAgentSchedule { foreach ($currentschedule in $InputObject) { $scheduleName = $currentschedule.Name $sourceServer = $currentschedule.Parent.Parent - $copySharedScheduleStatus = [pscustomobject]@{ + $copySharedScheduleStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Type = "Agent Schedule" diff --git a/public/Copy-DbaAgentServer.ps1 b/public/Copy-DbaAgentServer.ps1 index df2ee2cf08..ea9ef03fbd 100644 --- a/public/Copy-DbaAgentServer.ps1 +++ b/public/Copy-DbaAgentServer.ps1 @@ -154,7 +154,7 @@ function Copy-DbaAgentServer { #> <# Here are the properties which must be migrated separately #> - $copyAgentPropStatus = [pscustomobject]@{ + $copyAgentPropStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = "Server level properties" diff --git a/public/Copy-DbaBackupDevice.ps1 b/public/Copy-DbaBackupDevice.ps1 index 705cab7b6e..a96ee6e683 100644 --- a/public/Copy-DbaBackupDevice.ps1 +++ b/public/Copy-DbaBackupDevice.ps1 @@ -116,7 +116,7 @@ function Copy-DbaBackupDevice { foreach ($currentBackupDevice in $serverBackupDevices) { $deviceName = $currentBackupDevice.Name - $copyBackupDeviceStatus = [pscustomobject]@{ + $copyBackupDeviceStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $deviceName diff --git a/public/Copy-DbaCredential.ps1 b/public/Copy-DbaCredential.ps1 index 7b15dcc1ed..1f354b66bf 100644 --- a/public/Copy-DbaCredential.ps1 +++ b/public/Copy-DbaCredential.ps1 @@ -167,7 +167,7 @@ function Copy-DbaCredential { foreach ($cred in $credentialList) { $credentialName = $cred.Name - $copyCredentialStatus = [pscustomobject]@{ + $copyCredentialStatus = [PSCustomObject]@{ SourceServer = $sourceServer.DomainInstanceName DestinationServer = $destServer.DomainInstanceName Type = "Credential" diff --git a/public/Copy-DbaCustomError.ps1 b/public/Copy-DbaCustomError.ps1 index cc2cc2b1db..7f4b65673b 100644 --- a/public/Copy-DbaCustomError.ps1 +++ b/public/Copy-DbaCustomError.ps1 @@ -125,7 +125,7 @@ function Copy-DbaCustomError { $customErrorId = $currentCustomError.ID $language = $currentCustomError.Language.ToString() - $copyCustomErrorStatus = [pscustomobject]@{ + $copyCustomErrorStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Type = "Custom error" diff --git a/public/Copy-DbaDataCollector.ps1 b/public/Copy-DbaDataCollector.ps1 index ef3359dc78..2b209ff6cb 100644 --- a/public/Copy-DbaDataCollector.ps1 +++ b/public/Copy-DbaDataCollector.ps1 @@ -135,7 +135,7 @@ function Copy-DbaDataCollector { $NoServerReconfig = $true <# for future use when this support is added #> - $copyServerConfigStatus = [pscustomobject]@{ + $copyServerConfigStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $userName @@ -182,7 +182,7 @@ function Copy-DbaDataCollector { foreach ($set in $storeCollectionSets) { $collectionName = $set.Name - $copyCollectionSetStatus = [pscustomobject]@{ + $copyCollectionSetStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $collectionName diff --git a/public/Copy-DbaDatabase.ps1 b/public/Copy-DbaDatabase.ps1 index 90bf665e02..d62450d843 100644 --- a/public/Copy-DbaDatabase.ps1 +++ b/public/Copy-DbaDatabase.ps1 @@ -44,7 +44,7 @@ function Copy-DbaDatabase { If this switch is enabled, all user databases will be migrated. System and support databases will not be migrated. Requires -BackupRestore or -DetachAttach. .PARAMETER BackupRestore - If this switch is enabled, the copy-only backup and restore method will be used to migrate the database(s). This method requires that you specify -SharedPath in a valid UNC format (\\server\share). + If this switch is enabled, the copy-only backup and restore method will be used to migrate the database(s). This method requires that you specify either -SharedPath or -UseLastBackup. Backups will be immediately deleted after use unless -NoBackupCleanup is specified. @@ -273,6 +273,10 @@ function Copy-DbaDatabase { begin { $CopyOnly = -not $NoCopyOnly + if (-not $InputObject -and -not $Source) { + Stop-Function -Message "With no piped input a -Source must be specified." + return + } if ($BackupRestore -and (-not $SharedPath -and -not $UseLastBackup)) { Stop-Function -Message "When using -BackupRestore, you must specify -SharedPath or -UseLastBackup" return @@ -448,7 +452,7 @@ function Copy-DbaDatabase { $dbcollection.Add($($db.Name), $location) } - $fileStructure = [pscustomobject]@{ + $fileStructure = [PSCustomObject]@{ "databases" = $dbcollection } Write-Progress -Id 1 -Activity "Processing database file structure" -Status "Completed" -Completed @@ -709,7 +713,6 @@ function Copy-DbaDatabase { $Database = $InputObject.Name } - if ($Database -contains "master" -or $Database -contains "msdb" -or $Database -contains "tempdb") { Stop-Function -Message "Migrating system databases is not currently supported." -Continue } @@ -994,11 +997,11 @@ function Copy-DbaDatabase { $filestructure.databases[$dbName].Destination.$key.physical = Join-DbaPath -Path $SplitPath -ChildPath $splitFileName } - $copyDatabaseStatus = [pscustomobject]@{ + $copyDatabaseStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $dbName - DestinationDatabase = $DestinationDbname + DestinationDatabase = $destinationDbName Type = "Database" Status = $null Notes = $null @@ -1097,26 +1100,26 @@ function Copy-DbaDatabase { continue } - if (($null -ne $destServer.Databases[$DestinationdbName]) -and !$force -and !$WithReplace -and !$Continue) { - if ($Pscmdlet.ShouldProcess($destinstance, "$DestinationdbName exists at destination. Use -Force to drop and migrate. Aborting routine for this database.")) { - Write-Message -Level Verbose -Message "$DestinationdbName exists at destination. Use -Force to drop and migrate. Aborting routine for this database." + if (($null -ne $destServer.Databases[$destinationDbName]) -and !$force -and !$WithReplace -and !$Continue) { + if ($Pscmdlet.ShouldProcess($destinstance, "$destinationDbName exists at destination. Use -Force to drop and migrate. Aborting routine for this database.")) { + Write-Message -Level Verbose -Message "$destinationDbName exists at destination. Use -Force to drop and migrate. Aborting routine for this database." $copyDatabaseStatus.Status = "Skipped" $copyDatabaseStatus.Notes = "Already exists on destination" $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject } continue - } elseif ($null -ne $destServer.Databases[$DestinationdbName] -and $force) { - if ($sourceServer.Name -eq $destServer.Name -and $sourceServer.Databases[$DestinationdbName].Name -eq $destServer.Databases[$DestinationdbName].Name) { + } elseif ($null -ne $destServer.Databases[$destinationDbName] -and $force) { + if ($sourceServer.Name -eq $destServer.Name -and $dbName -eq $destinationDbName) { Write-Message -Level Verbose -Message "Source and destination database are the same. Aborting routine for this database." $copyDatabaseStatus.Status = "Failed" $copyDatabaseStatus.Notes = "Source and destination database are the same." $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject continue } - if ($Pscmdlet.ShouldProcess($destinstance, "DROP DATABASE $DestinationdbName")) { - Write-Message -Level Verbose -Message "$DestinationdbName already exists. -Force was specified. Dropping $DestinationdbName on $destinstance." - $removeresult = Remove-DbaDatabase -SqlInstance $destserver -Database $DestinationdbName -Confirm:$false + if ($Pscmdlet.ShouldProcess($destinstance, "DROP DATABASE $destinationDbName")) { + Write-Message -Level Verbose -Message "$destinationDbName already exists. -Force was specified. Dropping $destinationDbName on $destinstance." + $removeresult = Remove-DbaDatabase -SqlInstance $destserver -Database $destinationDbName -Confirm:$false $dropResult = $removeresult.Status -eq 'Dropped' if ($dropResult -eq $false) { @@ -1210,9 +1213,9 @@ function Copy-DbaDatabase { try { $msg = $null if ($miRestore) { - $restoreResultTmp = $backupTmpResult | Restore-DbaDatabase -SqlInstance $destServer -DatabaseName $DestinationdbName -TrustDbBackupHistory -WithReplace:$WithReplace -EnableException -AzureCredential $AzureCredential + $restoreResultTmp = $backupTmpResult | Restore-DbaDatabase -SqlInstance $destServer -DatabaseName $destinationDbName -TrustDbBackupHistory -WithReplace:$WithReplace -EnableException -AzureCredential $AzureCredential } else { - $restoreResultTmp = $backupTmpResult | Restore-DbaDatabase -SqlInstance $destServer -DatabaseName $DestinationdbName -ReuseSourceFolderStructure:$ReuseSourceFolderStructure -NoRecovery:$NoRecovery -TrustDbBackupHistory -WithReplace:$WithReplace -Continue:$Continue -EnableException -ReplaceDbNameInFile -AzureCredential $AzureCredential -KeepCDC:$KeepCDC -KeepReplication:$KeepReplication + $restoreResultTmp = $backupTmpResult | Restore-DbaDatabase -SqlInstance $destServer -DatabaseName $destinationDbName -ReuseSourceFolderStructure:$ReuseSourceFolderStructure -NoRecovery:$NoRecovery -TrustDbBackupHistory -WithReplace:$WithReplace -Continue:$Continue -EnableException -ReplaceDbNameInFile -AzureCredential $AzureCredential -KeepCDC:$KeepCDC -KeepReplication:$KeepReplication } } catch { $msg = $_.Exception.InnerException.InnerException.InnerException.InnerException.Message @@ -1355,46 +1358,46 @@ function Copy-DbaDatabase { } } } - $NewDatabase = Get-DbaDatabase -SqlInstance $destServer -database $DestinationdbName + $NewDatabase = Get-DbaDatabase -SqlInstance $destServer -database $destinationDbName $propfailures = @() # restore potentially lost settings if ($destServer.VersionMajor -ge 9 -and $NoRecovery -eq $false) { if ($sourceDbOwnerChaining -ne $NewDatabase.DatabaseOwnershipChaining) { - if ($Pscmdlet.ShouldProcess($destinstance, "Updating DatabaseOwnershipChaining on $DestinationdbName")) { + if ($Pscmdlet.ShouldProcess($destinstance, "Updating DatabaseOwnershipChaining on $destinationDbName")) { try { $NewDatabase.DatabaseOwnershipChaining = $sourceDbOwnerChaining $NewDatabase.Alter() - Write-Message -Level Verbose -Message "Successfully updated DatabaseOwnershipChaining for $sourceDbOwnerChaining on $DestinationdbName on $destinstance." + Write-Message -Level Verbose -Message "Successfully updated DatabaseOwnershipChaining for $sourceDbOwnerChaining on $destinationDbName on $destinstance." } catch { - Write-Message -Level Warning -Message "Failed to update DatabaseOwnershipChaining for $sourceDbOwnerChaining on $DestinationdbName on $destinstance." + Write-Message -Level Warning -Message "Failed to update DatabaseOwnershipChaining for $sourceDbOwnerChaining on $destinationDbName on $destinstance." $propfailures += "Ownership chaining" } } } if ($sourceDbTrustworthy -ne $NewDatabase.Trustworthy) { - if ($Pscmdlet.ShouldProcess($destinstance, "Updating Trustworthy on $DestinationdbName")) { + if ($Pscmdlet.ShouldProcess($destinstance, "Updating Trustworthy on $destinationDbName")) { try { $NewDatabase.Trustworthy = $sourceDbTrustworthy $NewDatabase.Alter() - Write-Message -Level Verbose -Message "Successfully updated Trustworthy to $sourceDbTrustworthy for $DestinationdbName on $destinstance" + Write-Message -Level Verbose -Message "Successfully updated Trustworthy to $sourceDbTrustworthy for $destinationDbName on $destinstance" } catch { - Write-Message -Level Warning -Message "Failed to update Trustworthy to $sourceDbTrustworthy for $DestinationdbName on $destinstance." + Write-Message -Level Warning -Message "Failed to update Trustworthy to $sourceDbTrustworthy for $destinationDbName on $destinstance." $propfailures += "Trustworthy" } } } if ($sourceDbBrokerEnabled -ne $NewDatabase.BrokerEnabled) { - if ($Pscmdlet.ShouldProcess($destinstance, "Updating BrokerEnabled on $DestinationDbName")) { + if ($Pscmdlet.ShouldProcess($destinstance, "Updating BrokerEnabled on $destinationDbName")) { try { $NewDatabase.BrokerEnabled = $sourceDbBrokerEnabled $NewDatabase.Alter() - Write-Message -Level Verbose -Message "Successfully updated BrokerEnabled to $sourceDbBrokerEnabled for $DestinationdbName on $destinstance." + Write-Message -Level Verbose -Message "Successfully updated BrokerEnabled to $sourceDbBrokerEnabled for $destinationDbName on $destinstance." } catch { - Write-Message -Level Warning -Message "Failed to update BrokerEnabled to $sourceDbBrokerEnabled for $DestinationdbName on $destinstance." + Write-Message -Level Warning -Message "Failed to update BrokerEnabled to $sourceDbBrokerEnabled for $destinationDbName on $destinstance." $propfailures += "Message broker" } @@ -1403,15 +1406,15 @@ function Copy-DbaDatabase { } if ($sourceDbReadOnly -ne $NewDatabase.ReadOnly -and -not $NoRecovery) { - if ($Pscmdlet.ShouldProcess($destinstance, "Updating ReadOnly status on $DestinationdbName")) { + if ($Pscmdlet.ShouldProcess($destinstance, "Updating ReadOnly status on $destinationDbName")) { try { if ($sourceDbReadOnly) { - $result = Set-DbaDbState -SqlInstance $destserver -Database $DestinationdbName -ReadOnly -EnableException + $result = Set-DbaDbState -SqlInstance $destserver -Database $destinationDbName -ReadOnly -EnableException } else { - $result = Set-DbaDbState -SqlInstance $destserver -Database $DestinationdbName -ReadWrite -EnableException + $result = Set-DbaDbState -SqlInstance $destserver -Database $destinationDbName -ReadWrite -EnableException } } catch { - Write-Message -Level Verbose -Message "Failed to update ReadOnly status on $DestinationdbName." + Write-Message -Level Verbose -Message "Failed to update ReadOnly status on $destinationDbName." $propfailures = "Read only" } } @@ -1426,10 +1429,9 @@ function Copy-DbaDatabase { $copyDatabaseStatus | Select-DefaultView -Property DateTime, SourceServer, DestinationServer, Name, Type, Status, Notes -TypeName MigrationObject } - if ($SetSourceOffline -and $sourceServer.databases[$DestinationdbName].status -notlike '*offline*') { - if ($Pscmdlet.ShouldProcess($source, "Setting $DestinationdbName offline")) { - Stop-DbaProcess -SqlInstance $sourceServer -Database $DestinationdbName - Set-DbaDbState -SqlInstance $sourceServer -SqlCredential $SourceSqlCredential -database $DestinationdbName -Offline + if ($SetSourceOffline -and $sourceServer.databases[$dbName].status -notlike '*offline*') { + if ($Pscmdlet.ShouldProcess($source, "Setting $dbName offline")) { + Set-DbaDbState -SqlInstance $sourceServer -Database $dbName -Offline -Force } } diff --git a/public/Copy-DbaDbAssembly.ps1 b/public/Copy-DbaDbAssembly.ps1 index 8a42ede4bb..823b9ef620 100644 --- a/public/Copy-DbaDbAssembly.ps1 +++ b/public/Copy-DbaDbAssembly.ps1 @@ -147,7 +147,7 @@ function Copy-DbaDbAssembly { $dbName = $currentAssembly.Parent.Name $destDb = $destServer.Databases[$dbName] Write-Message -Level VeryVerbose -Message "Processing $assemblyName on $dbName" - $copyDbAssemblyStatus = [pscustomobject]@{ + $copyDbAssemblyStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name SourceDatabase = $dbName SourceDatabaseID = $currentAssembly.Parent.ID diff --git a/public/Copy-DbaDbCertificate.ps1 b/public/Copy-DbaDbCertificate.ps1 index 5cc909f028..3844405e9e 100644 --- a/public/Copy-DbaDbCertificate.ps1 +++ b/public/Copy-DbaDbCertificate.ps1 @@ -224,7 +224,7 @@ function Copy-DbaDbCertificate { $certname = $cert.Name Write-Message -Level VeryVerbose -Message "Processing $certname on $dbName" - $copyDbCertificateStatus = [pscustomobject]@{ + $copyDbCertificateStatus = [PSCustomObject]@{ SourceServer = $cert.Parent.Parent.Name SourceDatabase = $dbName SourceDatabaseID = $cert.Parent.ID @@ -287,7 +287,7 @@ function Copy-DbaDbCertificate { $tempKey = Join-DbaPath -SqlInstance $server -Path $SharedPath -ChildPath "$certname.pvk" if ((Test-DbaPath -SqlInstance $server -Path $tempPath) -and (Test-DbaPath -SqlInstance $server -Path $tempKey)) { - $export = [pscustomobject]@{ + $export = [PSCustomObject]@{ Path = Join-DbaPath -SqlInstance $server -Path $SharedPath -ChildPath "$certname.cer" Key = Join-DbaPath -SqlInstance $server -Path $SharedPath -ChildPath "$certname.pvk" } diff --git a/public/Copy-DbaDbMail.ps1 b/public/Copy-DbaDbMail.ps1 index e09d6509c8..1fc6ddb8d8 100644 --- a/public/Copy-DbaDbMail.ps1 +++ b/public/Copy-DbaDbMail.ps1 @@ -98,7 +98,7 @@ function Copy-DbaDbMail { param () Write-Message -Message "Migrating mail server configuration values." -Level Verbose - $copyMailConfigStatus = [pscustomobject]@{ + $copyMailConfigStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = "Server Configuration" @@ -135,7 +135,7 @@ function Copy-DbaDbMail { $accountName = $account.name $newAccountName = $accountName -replace [Regex]::Escape($source), $destinstance Write-Message -Message "Updating account name from '$accountName' to '$newAccountName'." -Level Verbose - $copyMailAccountStatus = [pscustomobject]@{ + $copyMailAccountStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $accountName @@ -204,7 +204,7 @@ function Copy-DbaDbMail { $profileName = $profile.name $newProfileName = $profileName -replace [Regex]::Escape($source), $destinstance Write-Message -Message "Updating profile name from '$profileName' to '$newProfileName'." -Level Verbose - $copyMailProfileStatus = [pscustomobject]@{ + $copyMailProfileStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $profileName @@ -279,7 +279,7 @@ function Copy-DbaDbMail { Write-Message -Message "Migrating mail servers." -Level Verbose foreach ($mailServer in $sourceMailServers) { $mailServerName = $mailServer.name - $copyMailServerStatus = [pscustomobject]@{ + $copyMailServerStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $mailServerName @@ -432,7 +432,7 @@ function Copy-DbaDbMail { $destDbMailEnabled = ($destServer.Configuration.DatabaseMailEnabled).ConfigValue Write-Message -Message "$destServer DBMail configuration value: $destDbMailEnabled." -Level Verbose - $enableDBMailStatus = [pscustomobject]@{ + $enableDBMailStatus = [PSCustomObject]@{ SourceServer = $sourceServer.name DestinationServer = $destServer.name Name = "Enabled on Destination" diff --git a/public/Copy-DbaDbQueryStoreOption.ps1 b/public/Copy-DbaDbQueryStoreOption.ps1 index 9741fe66e7..6198896a42 100644 --- a/public/Copy-DbaDbQueryStoreOption.ps1 +++ b/public/Copy-DbaDbQueryStoreOption.ps1 @@ -143,7 +143,7 @@ function Copy-DbaDbQueryStoreOption { continue } Write-Message -Message "Processing destination database: $destDB on $destServer." -Level Verbose - $copyQueryStoreStatus = [pscustomobject]@{ + $copyQueryStoreStatus = [PSCustomObject]@{ SourceServer = $sourceServer.name SourceDatabase = $SourceDatabase SourceDatabaseID = $sourceDB.ID diff --git a/public/Copy-DbaDbTableData.ps1 b/public/Copy-DbaDbTableData.ps1 index 6ca97cf6a2..62326a466d 100644 --- a/public/Copy-DbaDbTableData.ps1 +++ b/public/Copy-DbaDbTableData.ps1 @@ -458,7 +458,7 @@ function Copy-DbaDbTableData { $bulkCopy.Dispose() $reader.Close() - [pscustomobject]@{ + [PSCustomObject]@{ SourceInstance = $server.Name SourceDatabase = $Database SourceDatabaseID = $sqlObject.Parent.ID diff --git a/public/Copy-DbaDbViewData.ps1 b/public/Copy-DbaDbViewData.ps1 index 04a0291aea..0f460ed9a9 100644 --- a/public/Copy-DbaDbViewData.ps1 +++ b/public/Copy-DbaDbViewData.ps1 @@ -203,4 +203,4 @@ function Copy-DbaDbViewData { process { Copy-DbaDbTableData @PSBoundParameters } -} +} \ No newline at end of file diff --git a/public/Copy-DbaEndpoint.ps1 b/public/Copy-DbaEndpoint.ps1 index 2d47f099b0..4d9e909ed0 100644 --- a/public/Copy-DbaEndpoint.ps1 +++ b/public/Copy-DbaEndpoint.ps1 @@ -117,7 +117,7 @@ function Copy-DbaEndpoint { foreach ($currentEndpoint in $serverEndpoints) { $endpointName = $currentEndpoint.Name - $copyEndpointStatus = [pscustomobject]@{ + $copyEndpointStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $endpointName diff --git a/public/Copy-DbaInstanceAudit.ps1 b/public/Copy-DbaInstanceAudit.ps1 index 8aae160290..924184dde5 100644 --- a/public/Copy-DbaInstanceAudit.ps1 +++ b/public/Copy-DbaInstanceAudit.ps1 @@ -124,7 +124,7 @@ function Copy-DbaInstanceAudit { foreach ($currentAudit in $serverAudits) { $auditName = $currentAudit.Name - $copyAuditStatus = [pscustomobject]@{ + $copyAuditStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $auditName diff --git a/public/Copy-DbaInstanceAuditSpecification.ps1 b/public/Copy-DbaInstanceAuditSpecification.ps1 index 38aaf1bd72..693e3f2bf5 100644 --- a/public/Copy-DbaInstanceAuditSpecification.ps1 +++ b/public/Copy-DbaInstanceAuditSpecification.ps1 @@ -130,7 +130,7 @@ function Copy-DbaInstanceAuditSpecification { foreach ($auditSpec in $AuditSpecifications) { $auditSpecName = $auditSpec.Name - $copyAuditSpecStatus = [pscustomobject]@{ + $copyAuditSpecStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Type = "Server Audit Specification" diff --git a/public/Copy-DbaInstanceTrigger.ps1 b/public/Copy-DbaInstanceTrigger.ps1 index e3a188ccf6..e5e94f2df0 100644 --- a/public/Copy-DbaInstanceTrigger.ps1 +++ b/public/Copy-DbaInstanceTrigger.ps1 @@ -123,7 +123,7 @@ function Copy-DbaInstanceTrigger { foreach ($trigger in $serverTriggers) { $triggerName = $trigger.Name - $copyTriggerStatus = [pscustomobject]@{ + $copyTriggerStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $triggerName diff --git a/public/Copy-DbaLinkedServer.ps1 b/public/Copy-DbaLinkedServer.ps1 index bbee9b17fd..cbaaf29ced 100644 --- a/public/Copy-DbaLinkedServer.ps1 +++ b/public/Copy-DbaLinkedServer.ps1 @@ -114,7 +114,7 @@ function Copy-DbaLinkedServer { if ($ExcludePassword) { $sourcelogins = @() foreach ($svr in $sourceServer.LinkedServers) { - $sourcelogins += [pscustomobject]@{ + $sourcelogins += [PSCustomObject]@{ Name = $sourcelogin.Name Identity = $sourcelogin.LinkedServerLogins.RemoteUser Password = $null @@ -147,7 +147,7 @@ function Copy-DbaLinkedServer { $linkedServerProductName = $currentLinkedServer.ProductName $linkedServerDataSource = $currentLinkedServer.DataSource - $copyLinkedServer = [pscustomobject]@{ + $copyLinkedServer = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $linkedServerName diff --git a/public/Copy-DbaLogin.ps1 b/public/Copy-DbaLogin.ps1 index 9bdc164b61..889ed60fff 100644 --- a/public/Copy-DbaLogin.ps1 +++ b/public/Copy-DbaLogin.ps1 @@ -194,7 +194,7 @@ function Copy-DbaLogin { $newUserName = $Login.name } - $copyLoginStatus = [pscustomobject]@{ + $copyLoginStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Type = "Login - $($Login.LoginType)" diff --git a/public/Copy-DbaPolicyManagement.ps1 b/public/Copy-DbaPolicyManagement.ps1 index ddc9789d5b..87d0ec036e 100644 --- a/public/Copy-DbaPolicyManagement.ps1 +++ b/public/Copy-DbaPolicyManagement.ps1 @@ -167,7 +167,7 @@ function Copy-DbaPolicyManagement { foreach ($category in $storeCategories) { $categoryName = $category.Name - $copyCategoryStatus = [pscustomobject]@{ + $copyCategoryStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $categoryName @@ -214,7 +214,7 @@ function Copy-DbaPolicyManagement { foreach ($condition in $storeConditions) { $conditionName = $condition.Name - $copyConditionStatus = [pscustomobject]@{ + $copyConditionStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $conditionName @@ -283,7 +283,7 @@ function Copy-DbaPolicyManagement { foreach ($policy in $storePolicies) { $policyName = $policy.Name - $copyPolicyStatus = [pscustomobject]@{ + $copyPolicyStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $policyName diff --git a/public/Copy-DbaRegServer.ps1 b/public/Copy-DbaRegServer.ps1 index bd833e2102..fd2bfd2bbe 100644 --- a/public/Copy-DbaRegServer.ps1 +++ b/public/Copy-DbaRegServer.ps1 @@ -110,7 +110,7 @@ function Copy-DbaRegServer { $groupName = $sourceGroup.Name $destinationGroup = $destinationGroup.ServerGroups[$groupName] - $copyDestinationGroupStatus = [pscustomobject]@{ + $copyDestinationGroupStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $groupName @@ -167,7 +167,7 @@ function Copy-DbaRegServer { $instanceName = $instance.Name $serverName = $instance.ServerName $destinstance = $destServer.Name - $copyInstanceStatus = [pscustomobject]@{ + $copyInstanceStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $instanceName @@ -253,7 +253,7 @@ function Copy-DbaRegServer { if ($Pscmdlet.ShouldProcess($destinstance, "Copying group $fromSubGroupName")) { $toSubGroup = $destinationGroup.ServerGroups[$fromSubGroupName] - $copyGroupStatus = [pscustomobject]@{ + $copyGroupStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $fromSubGroupName diff --git a/public/Copy-DbaResourceGovernor.ps1 b/public/Copy-DbaResourceGovernor.ps1 index f282c4e5dc..f2320de53f 100644 --- a/public/Copy-DbaResourceGovernor.ps1 +++ b/public/Copy-DbaResourceGovernor.ps1 @@ -110,7 +110,7 @@ function Copy-DbaResourceGovernor { } $destClassifierFunction = Get-DbaRgClassifierFunction -SqlInstance $destServer - $copyResourceGovSetting = [pscustomobject]@{ + $copyResourceGovSetting = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Type = "Resource Governor Settings" @@ -120,7 +120,7 @@ function Copy-DbaResourceGovernor { DateTime = [DbaDateTime](Get-Date) } - $copyResourceGovClassifierFunc = [pscustomobject]@{ + $copyResourceGovClassifierFunc = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Type = "Resource Governor Settings" @@ -235,7 +235,7 @@ function Copy-DbaResourceGovernor { foreach ($pool in $pools) { $poolName = $pool.Name - $copyResourceGovPool = [pscustomobject]@{ + $copyResourceGovPool = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Type = "Resource Governor Pool" @@ -298,7 +298,7 @@ function Copy-DbaResourceGovernor { foreach ($workloadGroup in $workloadGroups) { $workgroupName = $workloadGroup.Name - $copyResourceGovWorkGroup = [pscustomobject]@{ + $copyResourceGovWorkGroup = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Type = "Resource Governor Pool Workgroup" @@ -357,7 +357,7 @@ function Copy-DbaResourceGovernor { } - $copyResourceGovReconfig = [pscustomobject]@{ + $copyResourceGovReconfig = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Type = "Reconfigure Resource Governor" diff --git a/public/Copy-DbaSpConfigure.ps1 b/public/Copy-DbaSpConfigure.ps1 index 7a1e1d81ac..4f809e4eac 100644 --- a/public/Copy-DbaSpConfigure.ps1 +++ b/public/Copy-DbaSpConfigure.ps1 @@ -114,7 +114,7 @@ function Copy-DbaSpConfigure { $sConfiguredValue = $sourceProp.ConfiguredValue $requiresRestart = $sourceProp.IsDynamic - $copySpConfigStatus = [pscustomobject]@{ + $copySpConfigStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $sConfigName diff --git a/public/Copy-DbaSsisCatalog.ps1 b/public/Copy-DbaSsisCatalog.ps1 index 6fc0e0ef51..c7ee7cbbba 100644 --- a/public/Copy-DbaSsisCatalog.ps1 +++ b/public/Copy-DbaSsisCatalog.ps1 @@ -273,10 +273,8 @@ function Copy-DbaSsisCatalog { } try { - $legacyconnstring = $sourceServer | New-DbaConnectionString -Legacy - $sourcesqlconnection = New-Object System.Data.SqlClient.SqlConnection $legacyconnstring - $null = $sourcesqlconnection.Open() - $sourceSSIS = New-Object Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices $sourcesqlconnection + $sourceStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $sourceServer.ConnectionContext.SqlConnectionObject + $sourceSSIS = New-Object Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices $sourceStoreConnection } catch { Stop-Function -Message "There was an error connecting to the source integration services." -Target $sourceServer -ErrorRecord $_ return @@ -309,10 +307,8 @@ function Copy-DbaSsisCatalog { } try { - $legacyconnstring = $destinationConnection | New-DbaConnectionString -Legacy - $destsqlconnection = New-Object System.Data.SqlClient.SqlConnection $legacyconnstring - $null = $destsqlconnection.Open() - $destinationSSIS = New-Object Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices $destinationConnection + $destinationStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $destinationConnection.ConnectionContext.SqlConnectionObject + $destinationSSIS = New-Object Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices $destinationStoreConnection } catch { Stop-Function -Message "There was an error connecting to the destination integration services." -Target $destinationCon -ErrorRecord $_ } diff --git a/public/Copy-DbaSystemDbUserObject.ps1 b/public/Copy-DbaSystemDbUserObject.ps1 index 1eadabd57d..19f54e582f 100644 --- a/public/Copy-DbaSystemDbUserObject.ps1 +++ b/public/Copy-DbaSystemDbUserObject.ps1 @@ -129,7 +129,7 @@ function Copy-DbaSystemDbUserObject { $schemas = $smodb.Schemas | Where-Object IsSystemObject -ne $true foreach ($schema in $schemas) { - $copyobject = [pscustomobject]@{ + $copyobject = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $schema @@ -167,6 +167,7 @@ function Copy-DbaSystemDbUserObject { $transfer = New-Object Microsoft.SqlServer.Management.Smo.Transfer $smodb $null = $transfer.CopyAllObjects = $false $null = $transfer.Options.WithDependencies = $true + $null = $transfer.Options.ScriptOwner = $true $null = $transfer.ObjectList.Add($schema) if ($PSCmdlet.ShouldProcess($destInstance, "Attempting to add schema $($schema.Name) to $systemDb")) { try { @@ -186,7 +187,7 @@ function Copy-DbaSystemDbUserObject { } foreach ($table in $tables) { - $copyobject = [pscustomobject]@{ + $copyobject = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $table @@ -253,7 +254,7 @@ function Copy-DbaSystemDbUserObject { $sql = $userobject.Definition $schema = $userobject.SchemaName - $copyobject = [pscustomobject]@{ + $copyobject = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $name @@ -266,7 +267,7 @@ function Copy-DbaSystemDbUserObject { try { Write-Message -Level Verbose -Message "Searching for $name in $db on $destinstance" $result = Get-DbaModule -SqlInstance $destServer -ExcludeSystemObjects -Database $db | - Where-Object { $psitem.Name -eq $userobject.Name -and $psitem.Type -eq $userobject.Type } + Where-Object { $PSItem.Name -eq $userobject.Name -and $PSItem.Type -eq $userobject.Type } if ($result) { Write-Message -Level Verbose -Message "Found $name in $db on $destinstance" if (-not $Force) { @@ -409,4 +410,4 @@ function Copy-DbaSystemDbUserObject { } } } -} +} \ No newline at end of file diff --git a/public/Copy-DbaXESession.ps1 b/public/Copy-DbaXESession.ps1 index b8f4638857..3e758f6878 100644 --- a/public/Copy-DbaXESession.ps1 +++ b/public/Copy-DbaXESession.ps1 @@ -135,7 +135,7 @@ function Copy-DbaXESession { foreach ($session in $storeSessions) { $sessionName = $session.Name - $copyXeSessionStatus = [pscustomobject]@{ + $copyXeSessionStatus = [PSCustomObject]@{ SourceServer = $sourceServer.Name DestinationServer = $destServer.Name Name = $sessionName diff --git a/public/Disable-DbaForceNetworkEncryption.ps1 b/public/Disable-DbaForceNetworkEncryption.ps1 index 309e269fba..0671d61956 100644 --- a/public/Disable-DbaForceNetworkEncryption.ps1 +++ b/public/Disable-DbaForceNetworkEncryption.ps1 @@ -122,7 +122,7 @@ function Disable-DbaForceNetworkEncryption { Set-ItemProperty -Path $regPath -Name ForceEncryption -Value $false $forceencryption = (Get-ItemProperty -Path $regPath -Name ForceEncryption).ForceEncryption - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME InstanceName = $args[2] SqlInstance = $args[1] diff --git a/public/Disable-DbaHideInstance.ps1 b/public/Disable-DbaHideInstance.ps1 index 7debd77252..45b9931daa 100644 --- a/public/Disable-DbaHideInstance.ps1 +++ b/public/Disable-DbaHideInstance.ps1 @@ -116,7 +116,7 @@ function Disable-DbaHideInstance { Set-ItemProperty -Path $regPath -Name HideInstance -Value $false $HideInstance = (Get-ItemProperty -Path $regPath -Name HideInstance).HideInstance - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME InstanceName = $args[2] SqlInstance = $args[1] diff --git a/public/Disable-DbaReplDistributor.ps1 b/public/Disable-DbaReplDistributor.ps1 new file mode 100644 index 0000000000..f7a4e3bd4a --- /dev/null +++ b/public/Disable-DbaReplDistributor.ps1 @@ -0,0 +1,95 @@ +function Disable-DbaReplDistributor { + <# + .SYNOPSIS + Disables replication distribution for the target SQL instances. + + .DESCRIPTION + Disables replication distribution for the target SQL instances. + + .PARAMETER SqlInstance + The target SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER Force + Specify whether or not replication objects are removed from the server, even if a remote Distributor cannot be reached. + + If true, the publishing and Distributor configuration at the current server is uninstalled regardless of whether or not dependent publishing and distribution objects are uninstalled. + + If false, the publisher and distribution databases must already be uninstalled, and no local databases are enabled for publishing. + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .PARAMETER WhatIf + If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. + + .PARAMETER Confirm + If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. + + .NOTES + Tags: repl, Replication + Author: Jess Pomfret (@jpomfret), jesspomfret.com + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/Disable-DbaReplDistributor + + .EXAMPLE + PS C:\> Disable-DbaReplDistributor -SqlInstance mssql1 + + Disables replication distribution for the mssql1 instance. + + .EXAMPLE + PS C:\> $cred = Get-Credential sqladmin + PS C:\> Disable-DbaReplDistributor -SqlInstance mssql1, mssql2 -SqlCredential $cred -Force + + Disables replication distribution for the mssql1 and mssql2 instances using a sql login. Specifies force so the publishing and Distributor configuration at the current server is uninstalled regardless of whether or not dependent publishing and distribution objects are uninstalled. + + #> + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] + param ( + [Parameter(Mandatory, ValueFromPipeline)] + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [switch]$Force, + [switch]$EnableException + ) + process { + foreach ($instance in $SqlInstance) { + + $replServer = Get-DbaReplServer -SqlInstance $instance -SqlCredential $SqlCredential -EnableException:$EnableException + + Write-Message -Level Verbose -Message "Disabling and removing replication distribution for $instance" + + if ($replServer.IsDistributor) { + try { + if ($PSCmdlet.ShouldProcess($instance, "Disabling and removing distribution on $instance")) { + # remove any connections to the distribution database + $null = Get-DbaProcess -SqlInstance $instance -SqlCredential $SqlCredential -Database $replServer.DistributionDatabases.name -EnableException:$EnableException | Stop-DbaProcess -EnableException:$EnableException + # uninstall distribution + $replServer.UninstallDistributor($Force) + } + } catch { + Stop-Function -Message "Unable to disable replication distribution" -ErrorRecord $_ -Target $instance -Continue + } + + $replServer.Refresh() + $replServer + + } else { + Stop-Function -Message "$instance isn't currently enabled for distributing." -Target $instance -Continue + } + } + } +} \ No newline at end of file diff --git a/public/Disable-DbaReplPublishing.ps1 b/public/Disable-DbaReplPublishing.ps1 new file mode 100644 index 0000000000..1970881893 --- /dev/null +++ b/public/Disable-DbaReplPublishing.ps1 @@ -0,0 +1,92 @@ +function Disable-DbaReplPublishing { + <# + .SYNOPSIS + Disables publishing for the target SQL instances. + + .DESCRIPTION + Disables publishing for the target SQL instances. + + .PARAMETER SqlInstance + The target SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER Force + Specifies whether the Publisher is uninstalled from the Distributor without verifying that Publisher has also uninstalled the Distributor, if the Publisher is on a separate server. + If true, all the replication objects associated with the Publisher are dropped even if the Publisher is on a remote server that cannot be reached. + If false, replication first verifies that the remote Publisher has uninstalled the Distributor. + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .PARAMETER WhatIf + If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. + + .PARAMETER Confirm + If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. + + .NOTES + Tags: repl, Replication + Author: Jess Pomfret (@jpomfret), jesspomfret.com + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/Disable-DbaReplPublishing + + .EXAMPLE + PS C:\> Disable-DbaReplPublishing -SqlInstance mssql1 + + Disables replication distribution for the mssql1 instance. + + .EXAMPLE + PS C:\> $cred = Get-Credential sqladmin + PS C:\> Disable-DbaReplPublishing -SqlInstance mssql1, mssql2 -SqlCredential $cred -Force + + Disables replication distribution for the mssql1 and mssql2 instances using a sql login. + + Specifies force so all the replication objects associated with the Publisher are dropped even + if the Publisher is on a remote server that cannot be reached. + #> + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] + param ( + [Parameter(Mandatory, ValueFromPipeline)] + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [switch]$Force, + [switch]$EnableException + ) + process { + foreach ($instance in $SqlInstance) { + + $replServer = Get-DbaReplServer -SqlInstance $instance -SqlCredential $SqlCredential -EnableException:$EnableException + + Write-Message -Level Verbose -Message "Disabling and removing publishing for $instance" + + if ($replServer.IsPublisher) { + try { + if ($PSCmdlet.ShouldProcess($instance, "Disabling and removing publishing on $instance")) { + $replServer.DistributionPublishers.Remove($Force) + } + + $replServer.Refresh() + $replServer + + } catch { + Stop-Function -Message "Unable to disable replication publishing" -ErrorRecord $_ -Target $instance -Continue + } + } else { + Stop-Function -Message "$instance isn't currently enabled for publishing." -Continue -ContinueLabel main -Target $instance -Category ObjectNotFound + } + } + } +} \ No newline at end of file diff --git a/public/Disable-DbaTraceFlag.ps1 b/public/Disable-DbaTraceFlag.ps1 index 2c3e17e32d..2425494711 100644 --- a/public/Disable-DbaTraceFlag.ps1 +++ b/public/Disable-DbaTraceFlag.ps1 @@ -64,7 +64,7 @@ function Disable-DbaTraceFlag { $current = Get-DbaTraceFlag -SqlInstance $server -EnableException foreach ($tf in $TraceFlag) { - $TraceFlagInfo = [pscustomobject]@{ + $TraceFlagInfo = [PSCustomObject]@{ SourceServer = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -95,4 +95,4 @@ function Disable-DbaTraceFlag { } } } -} +} \ No newline at end of file diff --git a/public/Disconnect-DbaInstance.ps1 b/public/Disconnect-DbaInstance.ps1 index c0a76d1b60..ff56ac55ef 100644 --- a/public/Disconnect-DbaInstance.ps1 +++ b/public/Disconnect-DbaInstance.ps1 @@ -75,7 +75,7 @@ function Disconnect-DbaInstance { Write-Message -Level Verbose -Message "removing from connection hash" $null = $script:connectionhash.Remove($server.ConnectionContext.ConnectionString) } - [pscustomobject]@{ + [PSCustomObject]@{ SqlInstance = $server.Name ConnectionString = (Hide-ConnectionString -ConnectionString $server.ConnectionContext.ConnectionString) ConnectionType = $server.GetType().FullName @@ -94,7 +94,7 @@ function Disconnect-DbaInstance { $null = $script:connectionhash.Remove($server.ConnectionString) } - [pscustomobject]@{ + [PSCustomObject]@{ SqlInstance = $server.DataSource ConnectionString = (Hide-ConnectionString -ConnectionString $server.ConnectionString) ConnectionType = $server.GetType().FullName diff --git a/public/Dismount-DbaDatabase.ps1 b/public/Dismount-DbaDatabase.ps1 index e004784b84..1b86d9047a 100644 --- a/public/Dismount-DbaDatabase.ps1 +++ b/public/Dismount-DbaDatabase.ps1 @@ -197,7 +197,7 @@ function Dismount-DbaDatabase { $dbID = $db.ID $server.DetachDatabase($db.Name, $UpdateStatistics) - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Enable-DbaForceNetworkEncryption.ps1 b/public/Enable-DbaForceNetworkEncryption.ps1 index e64757c7b1..901bb4107e 100644 --- a/public/Enable-DbaForceNetworkEncryption.ps1 +++ b/public/Enable-DbaForceNetworkEncryption.ps1 @@ -122,7 +122,7 @@ function Enable-DbaForceNetworkEncryption { Set-ItemProperty -Path $regPath -Name ForceEncryption -Value $true $forceencryption = (Get-ItemProperty -Path $regPath -Name ForceEncryption).ForceEncryption - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME InstanceName = $args[2] SqlInstance = $args[1] diff --git a/public/Enable-DbaHideInstance.ps1 b/public/Enable-DbaHideInstance.ps1 index 0683495914..3813ba181a 100644 --- a/public/Enable-DbaHideInstance.ps1 +++ b/public/Enable-DbaHideInstance.ps1 @@ -116,7 +116,7 @@ function Enable-DbaHideInstance { Set-ItemProperty -Path $regPath -Name HideInstance -Value $true $hideInstance = (Get-ItemProperty -Path $regPath -Name HideInstance).HideInstance - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME InstanceName = $args[2] SqlInstance = $args[1] diff --git a/public/Enable-DbaReplDistributor.ps1 b/public/Enable-DbaReplDistributor.ps1 new file mode 100644 index 0000000000..902d3abbf8 --- /dev/null +++ b/public/Enable-DbaReplDistributor.ps1 @@ -0,0 +1,89 @@ +function Enable-DbaReplDistributor { + <# + .SYNOPSIS + Enables replication distribution for the target SQL instances. + + .DESCRIPTION + Enables replication distribution for the target SQL instances. + + .PARAMETER SqlInstance + The target SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER DistributionDatabase + Name of the distribution database that will be created. + + Default is 'distribution'. + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .PARAMETER WhatIf + If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. + + .PARAMETER Confirm + If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. + + .NOTES + Tags: repl, Replication + Author: Jess Pomfret (@jpomfret), jesspomfret.com + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/Enable-DbaReplDistributor + + .EXAMPLE + PS C:\> Enable-DbaReplDistributor -SqlInstance mssql1 + + Enables distribution for the mssql1 instance. + + .EXAMPLE + PS C:\> Enable-DbaReplDistributor -SqlInstance mssql1 -DistributionDatabase repDatabase + + Enables distribution for the mssql1 instance and names the distribution database repDatabase. + + #> + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param ( + [Parameter(Mandatory, ValueFromPipeline)] + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [string]$DistributionDatabase = 'distribution', + [switch]$EnableException + ) + process { + foreach ($instance in $SqlInstance) { + + $replServer = Get-DbaReplServer -SqlInstance $instance -SqlCredential $SqlCredential -EnableException:$EnableException + + Write-Message -Level Verbose -Message "Enabling replication distribution for $instance" + + try { + if ($PSCmdlet.ShouldProcess($instance, "Enabling distributor for $instance")) { + $distributionDb = New-Object Microsoft.SqlServer.Replication.DistributionDatabase + $distributionDb.ConnectionContext = $replServer.ConnectionContext + $distributionDb.Name = $DistributionDatabase + + #TODO: lots more properties to add as params + $replServer.InstallDistributor($null, $distributionDb) + + $replServer.Refresh() + $replServer + } + } catch { + Stop-Function -Message "Unable to enable replication distributor" -ErrorRecord $_ -Target $instance -Continue + } + } + } +} \ No newline at end of file diff --git a/public/Enable-DbaReplPublishing.ps1 b/public/Enable-DbaReplPublishing.ps1 new file mode 100644 index 0000000000..5995d335d5 --- /dev/null +++ b/public/Enable-DbaReplPublishing.ps1 @@ -0,0 +1,119 @@ +function Enable-DbaReplPublishing { + <# + .SYNOPSIS + Enables replication publishing for the target SQL instances. + + .DESCRIPTION + Enables replication publishing for the target SQL instances. + + .PARAMETER SqlInstance + The target SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER SnapshotShare + The share used to access snapshot files. + + The default is the ReplData folder within the InstallDataDirectory for the instance. + + .PARAMETER PublisherSqlLogin + If this is used the PublisherSecurity will be set to use this. + If not specified WindowsAuthentication will be used - this is the default, and recommended method. + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .PARAMETER WhatIf + If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. + + .PARAMETER Confirm + If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. + + .NOTES + Tags: repl, Replication + Author: Jess Pomfret (@jpomfret), jesspomfret.com + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/Enable-DbaReplPublishing + + .EXAMPLE + PS C:\> Enable-DbaReplPublishing -SqlInstance SqlBox1\Instance2 -StartupProcedure '[dbo].[StartUpProc1]' + + Attempts to set the procedure '[dbo].[StartUpProc1]' in the master database of SqlBox1\Instance2 for automatic execution when the instance is started. + + #> + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] + param ( + [Parameter(Mandatory, ValueFromPipeline)] + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [string]$SnapshotShare, + [PSCredential]$PublisherSqlLogin, + [switch]$EnableException + ) + process { + foreach ($instance in $SqlInstance) { + + $replServer = Get-DbaReplServer -SqlInstance $instance -SqlCredential $SqlCredential -EnableException:$EnableException + + Write-Message -Level Verbose -Message "Enabling replication publishing for $instance" + + if ($replServer.IsDistributor) { + try { + if ($PSCmdlet.ShouldProcess($instance, "Getting distribution information on $instance")) { + + $distPublisher = New-Object Microsoft.SqlServer.Replication.DistributionPublisher + $distPublisher.ConnectionContext = $replServer.ConnectionContext + $distPublisher.Name = $instance + $distPublisher.DistributionDatabase = $replServer.DistributionDatabases.Name + + if (Test-Bound SnapshotShare -Not) { + $SnapshotShare = Join-Path (Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential).InstallDataDirectory 'ReplData' + Write-Message -Level Verbose -Message ('No snapshot share specified, using default of {0}' -f $SnapshotShare) + } + + $distPublisher.WorkingDirectory = $SnapshotShare + } + + if ($PSCmdlet.ShouldProcess($instance, "Configuring PublisherSecurity on $instance")) { + if ($PublisherSqlLogin) { + Write-Message -Level Verbose -Message "Configuring with a SQLLogin for PublisherSecurity" + $distPublisher.PublisherSecurity.WindowsAuthentication = $false + $distPublisher.PublisherSecurity.SqlStandardLogin = $PublisherSqlLogin.UserName + $distPublisher.PublisherSecurity.SecureSqlStandardPassword = $PublisherSqlLogin.Password + + } else { + Write-Message -Level Verbose -Message "Configuring with WindowsAuth for PublisherSecurity" + $distPublisher.PublisherSecurity.WindowsAuthentication = $true + } + } + + if ($PSCmdlet.ShouldProcess($instance, "Enable publishing on $instance")) { + Write-Message -Level Debug -Message $distPublisher + # lots more properties to add as params + $distPublisher.Create() + + $replServer.Refresh() + $replServer + } + + } catch { + Stop-Function -Message "Unable to enable replication publishing" -ErrorRecord $_ -Target $instance -Continue + } + } else { + Stop-Function -Message "$instance isn't currently enabled for distributing. Please enable that first." -ErrorRecord $_ -Target $instance -Continue + } + } + } +} \ No newline at end of file diff --git a/public/Enable-DbaTraceFlag.ps1 b/public/Enable-DbaTraceFlag.ps1 index 0ab1e5852f..a69b78ae1a 100644 --- a/public/Enable-DbaTraceFlag.ps1 +++ b/public/Enable-DbaTraceFlag.ps1 @@ -100,4 +100,4 @@ function Enable-DbaTraceFlag { } } } -} +} \ No newline at end of file diff --git a/public/Expand-DbaDbLogFile.ps1 b/public/Expand-DbaDbLogFile.ps1 index 69fb8690fa..40fa8f63c6 100644 --- a/public/Expand-DbaDbLogFile.ps1 +++ b/public/Expand-DbaDbLogFile.ps1 @@ -486,7 +486,7 @@ function Expand-DbaDbLogFile { #Get the number of VLFs $currentVLFCount = Measure-DbaDbVirtualLogFile -SqlInstance $server -Database $db - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Export-DbaDacPackage.ps1 b/public/Export-DbaDacPackage.ps1 index a0c774ea3f..0fbd967e7e 100644 --- a/public/Export-DbaDacPackage.ps1 +++ b/public/Export-DbaDacPackage.ps1 @@ -274,7 +274,7 @@ function Export-DbaDacPackage { Stop-Function -Message "Standard output - $stderr"-Continue } } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Export-DbaExecutionPlan.ps1 b/public/Export-DbaExecutionPlan.ps1 index 4f4157ab94..acf02f678d 100644 --- a/public/Export-DbaExecutionPlan.ps1 +++ b/public/Export-DbaExecutionPlan.ps1 @@ -236,7 +236,7 @@ function Export-DbaExecutionPlan { $sqlHandle = "0x"; $row.sqlhandle | ForEach-Object { $sqlHandle += ("{0:X}" -f $_).PadLeft(2, "0") } $planhandle = "0x"; $row.planhandle | ForEach-Object { $planhandle += ("{0:X}" -f $_).PadLeft(2, "0") } - $object = [pscustomobject]@{ + $object = [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Export-DbaInstance.ps1 b/public/Export-DbaInstance.ps1 index 625e272ffc..b5229e3431 100644 --- a/public/Export-DbaInstance.ps1 +++ b/public/Export-DbaInstance.ps1 @@ -385,7 +385,7 @@ function Export-DbaInstance { Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Exporting replication settings" try { - $null = Export-DbaRepServerSetting -SqlInstance $instance -SqlCredential $SqlCredential -FilePath "$exportPath\replication.sql" -EnableException + $null = Export-DbaReplServerSetting -SqlInstance $instance -SqlCredential $SqlCredential -FilePath "$exportPath\replication.sql" -EnableException Get-ChildItem -ErrorAction Ignore -Path "$exportPath\replication.sql" } catch { Write-Message -Level Verbose -Message "Replication failed, skipping" diff --git a/public/Export-DbaLogin.ps1 b/public/Export-DbaLogin.ps1 index 9db9bcc78f..996150d1ac 100644 --- a/public/Export-DbaLogin.ps1 +++ b/public/Export-DbaLogin.ps1 @@ -262,7 +262,7 @@ function Export-DbaLogin { } $dbmap = $db.EnumLoginMappings() foreach ($el in $dbmap) { - $DbMapping += [pscustomobject]@{ + $DbMapping += [PSCustomObject]@{ Database = $db.Name UserName = $el.Username LoginName = $el.LoginName diff --git a/public/Export-DbaRepServerSetting.ps1 b/public/Export-DbaReplServerSetting.ps1 similarity index 90% rename from public/Export-DbaRepServerSetting.ps1 rename to public/Export-DbaReplServerSetting.ps1 index 7ab3ecc52d..77f59ca3f3 100644 --- a/public/Export-DbaRepServerSetting.ps1 +++ b/public/Export-DbaReplServerSetting.ps1 @@ -1,4 +1,4 @@ -function Export-DbaRepServerSetting { +function Export-DbaReplServerSetting { <# .SYNOPSIS Exports replication server settings to file. @@ -51,7 +51,7 @@ function Export-DbaRepServerSetting { Not real sure how to use this yet .PARAMETER InputObject - Allows piping from Get-DbaRepServer + Allows piping from Get-DbaReplServer .PARAMETER EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. @@ -59,7 +59,7 @@ function Export-DbaRepServerSetting { Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. .NOTES - Tags: Replication + Tags: Replication, Repl Author: Chrissy LeMaire (@cl), netnerds.net Website: https://dbatools.io @@ -67,15 +67,15 @@ function Export-DbaRepServerSetting { License: MIT https://opensource.org/licenses/MIT .LINK - https://dbatools.io/Export-DbaRepServerSetting + https://dbatools.io/Export-DbaReplServerSetting .EXAMPLE - PS C:\> Export-DbaRepServerSetting -SqlInstance sql2017 -Path C:\temp\replication.sql + PS C:\> Export-DbaReplServerSetting -SqlInstance sql2017 -Path C:\temp\replication.sql Exports the replication settings on sql2017 to the file C:\temp\replication.sql .EXAMPLE - PS C:\> Get-DbaRepServer -SqlInstance sql2017 | Export-DbaRepServerSettings -Path C:\temp\replication.sql + PS C:\> Get-DbaReplServer -SqlInstance sql2017 | Export-DbaReplServerSetting -Path C:\temp\replication.sql Exports the replication settings on sql2017 to the file C:\temp\replication.sql @@ -104,7 +104,7 @@ function Export-DbaRepServerSetting { process { if (Test-FunctionInterrupt) { return } foreach ($instance in $SqlInstance) { - $InputObject += Get-DbaRepServer -SqlInstance $instance -SqlCredential $SqlCredential + $InputObject += Get-DbaReplServer -SqlInstance $instance -SqlCredential $SqlCredential -EnableException:$EnableException } foreach ($repserver in $InputObject) { diff --git a/public/Export-DbaXESession.ps1 b/public/Export-DbaXESession.ps1 index c0245478a1..5d5a41229a 100644 --- a/public/Export-DbaXESession.ps1 +++ b/public/Export-DbaXESession.ps1 @@ -160,7 +160,7 @@ function Export-DbaXESession { } if ($SqlInstance) { - $InputObject = Get-DbaXeSession -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Session $Session + $InputObject = Get-DbaXESession -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Session $Session } foreach ($xe in $InputObject) { diff --git a/public/Find-DbaInstance.ps1 b/public/Find-DbaInstance.ps1 index 0de3402d29..8274cd729e 100644 --- a/public/Find-DbaInstance.ps1 +++ b/public/Find-DbaInstance.ps1 @@ -574,7 +574,7 @@ function Find-DbaInstance { [CmdletBinding()] param ( [string]$DomainController, - [Pscredential]$Credential, + [PSCredential]$Credential, [string]$ComputerName = "*", [switch]$GetSPN ) @@ -641,7 +641,7 @@ function Find-DbaInstance { [CmdletBinding()] param ( [string]$DomainController, - [Pscredential]$Credential + [PSCredential]$Credential ) try { @@ -727,7 +727,7 @@ function Find-DbaInstance { #endregion Connect to browser service and receive response #region Parse Output - $Response | Select-String "(ServerName;(\w+);InstanceName;(\w+);IsClustered;(\w+);Version;(\d+\.\d+\.\d+\.\d+);(tcp;(\d+)){0,1})" -AllMatches | Select-Object -ExpandProperty Matches | ForEach-Object { + $Response | Select-String "(ServerName;([a-zA-Z0-9_-]+);InstanceName;(\w+);IsClustered;(\w+);Version;(\d+\.\d+\.\d+\.\d+);(tcp;(\d+)){0,1})" -AllMatches | Select-Object -ExpandProperty Matches | ForEach-Object { $obj = New-Object Dataplat.Dbatools.Discovery.DbaBrowserReply -Property @{ MachineName = $computer.ComputerName ComputerName = $_.Groups[2].Value @@ -1083,4 +1083,4 @@ function Find-DbaInstance { } $steppablePipeline.End() } -} \ No newline at end of file +} diff --git a/public/Find-DbaOrphanedFile.ps1 b/public/Find-DbaOrphanedFile.ps1 index c7a465ddee..c293d5e426 100644 --- a/public/Find-DbaOrphanedFile.ps1 +++ b/public/Find-DbaOrphanedFile.ps1 @@ -96,7 +96,7 @@ function Find-DbaOrphanedFile { param ( [Parameter(Mandatory, ValueFromPipeline)] [DbaInstanceParameter[]]$SqlInstance, - [pscredential]$SqlCredential, + [PSCredential]$SqlCredential, [string[]]$Path, [string[]]$FileType, [Parameter(ParameterSetName = 'LocalOnly')][switch]$LocalOnly, @@ -379,7 +379,7 @@ function Find-DbaOrphanedFile { if ($filename -in $systemfiles) { continue } - $result = [pscustomobject]@{ + $result = [PSCustomObject]@{ Server = $server.name ComputerName = $server.ComputerName InstanceName = $server.ServiceName diff --git a/public/Get-DbaAgBackupHistory.ps1 b/public/Get-DbaAgBackupHistory.ps1 index 836ce8a224..b8f04e88c9 100644 --- a/public/Get-DbaAgBackupHistory.ps1 +++ b/public/Get-DbaAgBackupHistory.ps1 @@ -124,7 +124,7 @@ function Get-DbaAgBackupHistory { [parameter(Mandatory, ValueFromPipeline)] [DbaInstanceParameter[]] $SqlInstance, - [PsCredential]$SqlCredential, + [PSCredential]$SqlCredential, [parameter(Mandatory)] [string]$AvailabilityGroup, [string[]]$Database, @@ -232,4 +232,4 @@ function Get-DbaAgBackupHistory { $AgResults } } -} +} \ No newline at end of file diff --git a/public/Get-DbaAgentAlert.ps1 b/public/Get-DbaAgentAlert.ps1 index 4a69ea9609..a4b637c51e 100644 --- a/public/Get-DbaAgentAlert.ps1 +++ b/public/Get-DbaAgentAlert.ps1 @@ -112,4 +112,4 @@ function Get-DbaAgentAlert { } } } -} +} \ No newline at end of file diff --git a/public/Get-DbaAgentJob.ps1 b/public/Get-DbaAgentJob.ps1 index 5113d60d3a..7792a9897b 100644 --- a/public/Get-DbaAgentJob.ps1 +++ b/public/Get-DbaAgentJob.ps1 @@ -172,4 +172,4 @@ function Get-DbaAgentJob { } } } -} +} \ No newline at end of file diff --git a/public/Get-DbaAgentJobHistory.ps1 b/public/Get-DbaAgentJobHistory.ps1 index 160ec10820..c9f5f468aa 100644 --- a/public/Get-DbaAgentJobHistory.ps1 +++ b/public/Get-DbaAgentJobHistory.ps1 @@ -243,7 +243,7 @@ function Get-DbaAgentJobHistory { $outmap[$out.Job][$out.StepId] = $out.OutputFileName } } - $outcome = [pscustomobject]@{ } + $outcome = [PSCustomObject]@{ } foreach ($execution in $executions) { $status = switch ($execution.RunStatus) { 0 { "Failed" } diff --git a/public/Get-DbaAgentJobOutputFile.ps1 b/public/Get-DbaAgentJobOutputFile.ps1 index 226257617f..c2fbfc1508 100644 --- a/public/Get-DbaAgentJobOutputFile.ps1 +++ b/public/Get-DbaAgentJobOutputFile.ps1 @@ -110,7 +110,7 @@ function Get-DbaAgentJobOutputFile { foreach ($j in $Jobs) { foreach ($step in $j.JobSteps) { if ($step.OutputFileName) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaBackupInformation.ps1 b/public/Get-DbaBackupInformation.ps1 index 82805d65a1..d4b187b09d 100644 --- a/public/Get-DbaBackupInformation.ps1 +++ b/public/Get-DbaBackupInformation.ps1 @@ -384,4 +384,4 @@ function Get-DbaBackupInformation { } $groupResults | Sort-Object -Property End -Descending } -} +} \ No newline at end of file diff --git a/public/Get-DbaBuild.ps1 b/public/Get-DbaBuild.ps1 index dc61c34c73..19b00d5b48 100644 --- a/public/Get-DbaBuild.ps1 +++ b/public/Get-DbaBuild.ps1 @@ -101,7 +101,7 @@ function Get-DbaBuild { [DbaInstanceParameter[]] $SqlInstance, - [PsCredential] + [PSCredential] $SqlCredential, [switch] diff --git a/public/Get-DbaClientAlias.ps1 b/public/Get-DbaClientAlias.ps1 index 0c10d921a0..54559da88e 100644 --- a/public/Get-DbaClientAlias.ps1 +++ b/public/Get-DbaClientAlias.ps1 @@ -100,7 +100,7 @@ function Get-DbaClientAlias { $value = Get-ItemPropertyValue -Path $connect -Name $entry $clean = $value.Replace('DBNMPNTW,', '').Replace('DBMSSOCN,', '') if ($value.StartsWith('DBMSSOCN')) { $protocol = 'TCP/IP' } else { $protocol = 'Named Pipes' } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME NetworkLibrary = $protocol ServerName = $clean diff --git a/public/Get-DbaComputerSystem.ps1 b/public/Get-DbaComputerSystem.ps1 index 649d5a5291..e497a785d2 100644 --- a/public/Get-DbaComputerSystem.ps1 +++ b/public/Get-DbaComputerSystem.ps1 @@ -175,4 +175,4 @@ function Get-DbaComputerSystem { } } } -} +} \ No newline at end of file diff --git a/public/Get-DbaConnectedInstance.ps1 b/public/Get-DbaConnectedInstance.ps1 index d0318908bd..10f91ebcc1 100644 --- a/public/Get-DbaConnectedInstance.ps1 +++ b/public/Get-DbaConnectedInstance.ps1 @@ -43,7 +43,7 @@ function Get-DbaConnectedInstance { } else { $pooling = $true } - [pscustomobject]@{ + [PSCustomObject]@{ SqlInstance = $instance ConnectionObject = $script:connectionhash[$key] ConnectionType = $value.GetType().FullName diff --git a/public/Get-DbaCpuUsage.ps1 b/public/Get-DbaCpuUsage.ps1 index d62258efea..e6a3885dd8 100644 --- a/public/Get-DbaCpuUsage.ps1 +++ b/public/Get-DbaCpuUsage.ps1 @@ -76,7 +76,7 @@ function Get-DbaCpuUsage { ) begin { # This can likely be enumerated but I don't know hows - $threadstates = [pscustomobject]@{ + $threadstates = [PSCustomObject]@{ 0 = 'Initialized. It is recognized by the microkernel.' 1 = 'Ready. It is prepared to run on the next available processor.' 2 = 'Running. It is executing.' @@ -87,7 +87,7 @@ function Get-DbaCpuUsage { 7 = 'Unknown. The thread state is unknown.' } - $threadwaitreasons = [pscustomobject]@{ + $threadwaitreasons = [PSCustomObject]@{ 0 = 'Executive' 1 = 'FreePage' 2 = 'PageIn' diff --git a/public/Get-DbaDbBackupHistory.ps1 b/public/Get-DbaDbBackupHistory.ps1 index 80760d6f44..779f469b53 100644 --- a/public/Get-DbaDbBackupHistory.ps1 +++ b/public/Get-DbaDbBackupHistory.ps1 @@ -155,7 +155,7 @@ function Get-DbaDbBackupHistory { [parameter(Mandatory, ValueFromPipeline)] [DbaInstanceParameter[]] $SqlInstance, - [PsCredential]$SqlCredential, + [PSCredential]$SqlCredential, [object[]]$Database, [object[]]$ExcludeDatabase, [switch]$IncludeCopyOnly, @@ -547,6 +547,7 @@ function Get-DbaDbBackupHistory { } else { $select = " SELECT + '' as AvailabilityGroupName, backupset.database_name AS [Database], (SELECT database_id FROM sys.databases WHERE name = backupset.database_name) AS DatabaseId, backupset.user_name AS Username, @@ -739,4 +740,4 @@ function Get-DbaDbBackupHistory { } } } -} +} \ No newline at end of file diff --git a/public/Get-DbaDbCompression.ps1 b/public/Get-DbaDbCompression.ps1 index c65b0a247e..e24d3a8e5f 100644 --- a/public/Get-DbaDbCompression.ps1 +++ b/public/Get-DbaDbCompression.ps1 @@ -106,7 +106,7 @@ function Get-DbaDbCompression { foreach ($obj in $tables) { if ($obj.HasHeapIndex) { foreach ($p in $obj.PhysicalPartitions) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -127,7 +127,7 @@ function Get-DbaDbCompression { foreach ($index in $obj.Indexes) { foreach ($p in $index.PhysicalPartitions) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaDbDetachedFileInfo.ps1 b/public/Get-DbaDbDetachedFileInfo.ps1 index b85a43a457..ad9e31b9f7 100644 --- a/public/Get-DbaDbDetachedFileInfo.ps1 +++ b/public/Get-DbaDbDetachedFileInfo.ps1 @@ -124,7 +124,7 @@ function Get-DbaDbDetachedFileInfo { } catch { Stop-Function -Message "$servername unable to enumerate database or log structure information for $filepath" -Continue } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $SqlInstance.ComputerName InstanceName = $SqlInstance.InstanceName SqlInstance = $SqlInstance.InputObject diff --git a/public/Get-DbaDbExtentDiff.ps1 b/public/Get-DbaDbExtentDiff.ps1 index cbaf724b46..65eb1158b2 100644 --- a/public/Get-DbaDbExtentDiff.ps1 +++ b/public/Get-DbaDbExtentDiff.ps1 @@ -122,7 +122,7 @@ function Get-DbaDbExtentDiff { FROM sys.dm_db_file_space_usage " $DBCCPageResults = $server.Query($DBCCPageQueryDMV, $db.Name) - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -156,7 +156,7 @@ function Get-DbaDbExtentDiff { } } $extents = Get-DbaExtent $dbExtents.Field - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaDbFileGrowth.ps1 b/public/Get-DbaDbFileGrowth.ps1 index 92c53199ec..0dee33c496 100644 --- a/public/Get-DbaDbFileGrowth.ps1 +++ b/public/Get-DbaDbFileGrowth.ps1 @@ -56,7 +56,7 @@ function Get-DbaDbFileGrowth { [CmdletBinding()] param ( [DbaInstanceParameter[]]$SqlInstance, - [PsCredential]$SqlCredential, + [PSCredential]$SqlCredential, [string[]]$Database, [parameter(ValueFromPipeline)] [Microsoft.SqlServer.Management.Smo.Database[]]$InputObject, @@ -73,4 +73,4 @@ function Get-DbaDbFileGrowth { $db | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Database, MaxSize, GrowthType, Growth, 'LogicalName as File', 'PhysicalName as FileName', State } } -} +} \ No newline at end of file diff --git a/public/Get-DbaDbLogSpace.ps1 b/public/Get-DbaDbLogSpace.ps1 index 2b15ad6162..0f9923e29f 100644 --- a/public/Get-DbaDbLogSpace.ps1 +++ b/public/Get-DbaDbLogSpace.ps1 @@ -107,7 +107,7 @@ Function Get-DbaDbLogSpace { } catch { Stop-Function -Message "Unable to collect log space data on $instance." -ErrorRecord $_ -Target $db -Continue } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -125,7 +125,7 @@ Function Get-DbaDbLogSpace { } foreach ($ls in $logspace) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaDbMirrorMonitor.ps1 b/public/Get-DbaDbMirrorMonitor.ps1 index 6f7ca54c66..8a070dc7c1 100644 --- a/public/Get-DbaDbMirrorMonitor.ps1 +++ b/public/Get-DbaDbMirrorMonitor.ps1 @@ -115,7 +115,7 @@ function Get-DbaDbMirrorMonitor { $results = $db.Parent.Query($sql) foreach ($result in $results) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $db.Parent.ComputerName InstanceName = $db.Parent.ServiceName SqlInstance = $db.Parent.DomainInstanceName diff --git a/public/Get-DbaDbServiceBrokerQueue.ps1 b/public/Get-DbaDbServiceBrokerQueue.ps1 index 0fd9b5b74a..ffe9eb39ce 100644 --- a/public/Get-DbaDbServiceBrokerQueue.ps1 +++ b/public/Get-DbaDbServiceBrokerQueue.ps1 @@ -103,4 +103,4 @@ function Get-DbaDbServiceBrokerQueue { } } } -} +} \ No newline at end of file diff --git a/public/Get-DbaDbServiceBrokerService.ps1 b/public/Get-DbaDbServiceBrokerService.ps1 index f6180c0b43..dcae2fb16b 100644 --- a/public/Get-DbaDbServiceBrokerService.ps1 +++ b/public/Get-DbaDbServiceBrokerService.ps1 @@ -103,4 +103,4 @@ function Get-DbaDbServiceBrokerService { } } } -} +} \ No newline at end of file diff --git a/public/Get-DbaDbSpace.ps1 b/public/Get-DbaDbSpace.ps1 index 831d267495..760d54bedf 100644 --- a/public/Get-DbaDbSpace.ps1 +++ b/public/Get-DbaDbSpace.ps1 @@ -100,19 +100,19 @@ function Get-DbaDbSpace { ,CASE is_percent_growth WHEN 1 THEN 'pct' WHEN 0 THEN 'MB' ELSE 'Unknown' END AS [GrowthType] ,CASE f.max_size WHEN -1 THEN 2147483648. ELSE CAST((f.max_size/128.0) AS FLOAT) END AS [MaxSizeMB] ,CAST((f.size/128.0) AS FLOAT) - CAST(CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS FLOAT) AS [SpaceBeforeAutoGrow] - ,CASE f.max_size WHEN (-1) + ,CASE f.max_size WHEN (-1) THEN CAST(((2147483648.) - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int))/128.0 AS FLOAT) ELSE CAST((f.max_size - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int))/128.0 AS FLOAT) END AS [SpaceBeforeMax] - ,CASE f.growth WHEN 0 THEN 0.00 - ELSE CASE f.is_percent_growth WHEN 0 - THEN CASE f.max_size + ,CASE f.growth WHEN 0 THEN 0.00 + ELSE CASE f.is_percent_growth WHEN 0 + THEN CASE f.max_size WHEN (-1) THEN CAST(((((2147483648.)-f.Size)/f.Growth)*f.Growth)/128.0 AS FLOAT) ELSE CAST((((f.max_size-f.Size)/f.Growth)*f.Growth)/128.0 AS FLOAT) END WHEN 1 - THEN CASE f.max_size + THEN CASE f.max_size WHEN (-1) THEN CAST(CONVERT([int],f.Size*power((1)+CONVERT([float],f.Growth)/(100),CONVERT([int],log10(CONVERT([float],(2147483648.))/CONVERT([float],f.Size))/log10((1)+CONVERT([float],f.Growth)/(100)))))/128.0 AS FLOAT) ELSE CAST(CONVERT([int],f.Size*power((1)+CONVERT([float],f.Growth)/(100),CONVERT([int],log10(CONVERT([float],f.Max_Size)/CONVERT([float],f.Size))/log10((1)+CONVERT([float],f.Growth)/(100)))))/128.0 AS FLOAT) @@ -120,13 +120,13 @@ function Get-DbaDbSpace { ELSE (0) END END AS [PossibleAutoGrowthMB] - , CASE f.max_size WHEN -1 THEN 0 + , CASE f.max_size WHEN -1 THEN 0 ELSE CASE f.growth WHEN 0 THEN (f.max_size - f.size)/128 - ELSE CASE f.is_percent_growth + ELSE CASE f.is_percent_growth WHEN 0 - THEN CAST((f.max_size - f.size - ( CONVERT(FLOAT,FLOOR((f.max_size-f.Size)/f.Growth)*f.Growth)))/128.0 AS FLOAT) - ELSE CAST((f.max_size - f.size - ( CONVERT([int],f.Size*power((1)+CONVERT([float],f.Growth)/(100),CONVERT([int],log10(CONVERT([float],f.Max_Size)/CONVERT([float],f.Size))/log10((1)+CONVERT([float],f.Growth)/(100)))))))/128.0 AS FLOAT) + THEN CAST((f.max_size - f.size - ( CONVERT(FLOAT,FLOOR((f.max_size-f.Size)/f.Growth)*f.Growth)))/128.0 AS FLOAT) + ELSE CAST((f.max_size - f.size - ( CONVERT([int],f.Size*power((1)+CONVERT([float],f.Growth)/(100),CONVERT([int],log10(CONVERT([float],f.Max_Size)/CONVERT([float],f.Size))/log10((1)+CONVERT([float],f.Growth)/(100)))))))/128.0 AS FLOAT) END END END AS [UnusableSpaceMB] @@ -185,7 +185,7 @@ function Get-DbaDbSpace { $UnusableSpace = [Math]::Round($row.UnusableSpaceMB) } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaDbState.ps1 b/public/Get-DbaDbState.ps1 index 60a0af57b3..dccb84b4dd 100644 --- a/public/Get-DbaDbState.ps1 +++ b/public/Get-DbaDbState.ps1 @@ -119,7 +119,7 @@ FROM sys.databases # "normal" hashtable doesn't account for case sensitivity $dbStatesHash = New-Object -TypeName System.Collections.Hashtable foreach ($db in $dbStates) { - $dbStatesHash.Add($db.Name, [pscustomobject]@{ + $dbStatesHash.Add($db.Name, [PSCustomObject]@{ Access = $db.Access Status = $db.Status RW = $db.RW diff --git a/public/Get-DbaDbView.ps1 b/public/Get-DbaDbView.ps1 index 457cdf62ae..0c00ce2eee 100644 --- a/public/Get-DbaDbView.ps1 +++ b/public/Get-DbaDbView.ps1 @@ -183,4 +183,4 @@ function Get-DbaDbView { } } } -} +} \ No newline at end of file diff --git a/public/Get-DbaDbVirtualLogFile.ps1 b/public/Get-DbaDbVirtualLogFile.ps1 index d603d69c93..9dea2ba9f4 100644 --- a/public/Get-DbaDbVirtualLogFile.ps1 +++ b/public/Get-DbaDbVirtualLogFile.ps1 @@ -108,7 +108,7 @@ function Get-DbaDbVirtualLogFile { $data = $db.Query("DBCC LOGINFO") foreach ($d in $data) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaEstimatedCompletionTime.ps1 b/public/Get-DbaEstimatedCompletionTime.ps1 index d309103005..747485938a 100644 --- a/public/Get-DbaEstimatedCompletionTime.ps1 +++ b/public/Get-DbaEstimatedCompletionTime.ps1 @@ -139,7 +139,7 @@ function Get-DbaEstimatedCompletionTime { Write-Message -Level Debug -Message $sql foreach ($row in ($server.Query($sql))) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaExecutionPlan.ps1 b/public/Get-DbaExecutionPlan.ps1 index c613223785..3880fb9617 100644 --- a/public/Get-DbaExecutionPlan.ps1 +++ b/public/Get-DbaExecutionPlan.ps1 @@ -172,7 +172,7 @@ function Get-DbaExecutionPlan { $planHandle = "0x"; $row.planhandle | ForEach-Object { $planHandle += ("{0:X}" -f $_).PadLeft(2, "0") } $planWarnings = $simple.QueryPlan.Warnings.PlanAffectingConvert; - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaExtendedProtection.ps1 b/public/Get-DbaExtendedProtection.ps1 index ef99f84276..1a268a7ffa 100644 --- a/public/Get-DbaExtendedProtection.ps1 +++ b/public/Get-DbaExtendedProtection.ps1 @@ -111,7 +111,7 @@ function Get-DbaExtendedProtection { $regPath = "Registry::HKEY_LOCAL_MACHINE\$($args[0])\MSSQLServer\SuperSocketNetLib" $extendedProtection = (Get-ItemProperty -Path $regPath -Name ExtendedProtection).ExtendedProtection - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME InstanceName = $args[2] SqlInstance = $args[1] diff --git a/public/Get-DbaFeature.ps1 b/public/Get-DbaFeature.ps1 index 0aef58df81..50b5c76a24 100644 --- a/public/Get-DbaFeature.ps1 +++ b/public/Get-DbaFeature.ps1 @@ -95,7 +95,7 @@ function Get-DbaFeature { $xml = [xml]($text) foreach ($result in $xml.ArrayOfDiscoveryInformation.DiscoveryInformation) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $computer Product = $result.Product Instance = $result.Instance diff --git a/public/Get-DbaFile.ps1 b/public/Get-DbaFile.ps1 index ab7175a655..3d8d87ebb5 100644 --- a/public/Get-DbaFile.ps1 +++ b/public/Get-DbaFile.ps1 @@ -193,7 +193,7 @@ function Get-DbaFile { $fullpath = $row.fullpath.Replace("\", $separator) $fullpath = $fullpath.Replace("\\", "\") $fullpath = $fullpath.Replace("//", "/") - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -209,7 +209,7 @@ function Get-DbaFile { $fullpath = $fullpath.Replace("\", $separator) $fullpath = $fullpath.Replace("\\", "\") $fullpath = $fullpath.Replace("//", "/") - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaForceNetworkEncryption.ps1 b/public/Get-DbaForceNetworkEncryption.ps1 index fe871b6869..963c086631 100644 --- a/public/Get-DbaForceNetworkEncryption.ps1 +++ b/public/Get-DbaForceNetworkEncryption.ps1 @@ -114,7 +114,7 @@ function Get-DbaForceNetworkEncryption { $cert = (Get-ItemProperty -Path $regPath -Name Certificate).Certificate $forceencryption = (Get-ItemProperty -Path $regPath -Name ForceEncryption).ForceEncryption - # [pscustomobject] doesn't always work, unsure why. so return hashtable then turn it into pscustomobject on client + # [PSCustomObject] doesn't always work, unsure why. so return hashtable then turn it into PSCustomObject on client @{ ComputerName = $env:COMPUTERNAME InstanceName = $args[2] @@ -127,7 +127,7 @@ function Get-DbaForceNetworkEncryption { try { $results = Invoke-Command2 -ComputerName $resolved.FullComputerName -Credential $Credential -ArgumentList $regRoot, $vsname, $instanceName -ScriptBlock $scriptBlock -ErrorAction Stop -Raw foreach ($result in $results) { - [pscustomobject]$result + [PSCustomObject]$result } } catch { Stop-Function -Message "Failed to connect to $($resolved.FullComputerName) using PowerShell remoting" -ErrorRecord $_ -Target $instance -Continue diff --git a/public/Get-DbaHelpIndex.ps1 b/public/Get-DbaHelpIndex.ps1 index ab9788b3dd..86d44d9cb9 100644 --- a/public/Get-DbaHelpIndex.ps1 +++ b/public/Get-DbaHelpIndex.ps1 @@ -557,24 +557,24 @@ function Get-DbaHelpIndex { DECLARE @AllResults TABLE ( RowNum INT , - FullObjectName NVARCHAR(300) , - IndexType NVARCHAR(256) , - IndexName NVARCHAR(256) , - KeyColumns NVARCHAR(2000) , - IncludeColumns NVARCHAR(2000) , - FilterDefinition NVARCHAR(100) , - [FillFactor] TINYINT , - DataCompression CHAR(4) , - IndexReads BIGINT , - IndexUpdates BIGINT , - SizeKB BIGINT , - IndexRows BIGINT , - IndexLookups BIGINT , - MostRecentlyUsed DATETIME , - StatsSampleRows BIGINT , - StatsRowMods BIGINT , - HistogramSteps INT , - StatsLastUpdated DATETIME , + FullObjectName NVARCHAR(300) , + IndexType NVARCHAR(256) , + IndexName NVARCHAR(256) , + KeyColumns NVARCHAR(2000) , + IncludeColumns NVARCHAR(2000) , + FilterDefinition NVARCHAR(100) , + [FillFactor] TINYINT , + DataCompression CHAR(4) , + IndexReads BIGINT , + IndexUpdates BIGINT , + SizeKB BIGINT , + IndexRows BIGINT , + IndexLookups BIGINT , + MostRecentlyUsed DATETIME , + StatsSampleRows BIGINT , + StatsRowMods BIGINT , + HistogramSteps INT , + StatsLastUpdated DATETIME , object_id BIGINT , index_id BIGINT ); @@ -859,7 +859,7 @@ function Get-DbaHelpIndex { ci.IndexRows , ci.FullObjectName ), AllResults AS - ( SELECT c.FullObjectName , + ( SELECT c.FullObjectName , ISNULL(IndexType, 'STATISTICS') AS IndexType , ISNULL(IndexName, '') AS IndexName , ISNULL(KeyColumns, '') AS KeyColumns , @@ -972,7 +972,7 @@ function Get-DbaHelpIndex { FROM @AllResults a JOIN sys.sysindexes i ON a.object_id = i.id AND a.index_id = i.indid; - SELECT FullObjectName , + SELECT FullObjectName , IndexType , IndexName , KeyColumns , @@ -1035,7 +1035,7 @@ function Get-DbaHelpIndex { $recentlyused = $null } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -1071,7 +1071,7 @@ function Get-DbaHelpIndex { $recentlyused = $null } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaHideInstance.ps1 b/public/Get-DbaHideInstance.ps1 index 102c3064a2..7a28bac939 100644 --- a/public/Get-DbaHideInstance.ps1 +++ b/public/Get-DbaHideInstance.ps1 @@ -113,7 +113,7 @@ function Get-DbaHideInstance { $regPath = "Registry::HKEY_LOCAL_MACHINE\$($args[0])\MSSQLServer\SuperSocketNetLib" $HideInstance = (Get-ItemProperty -Path $regPath -Name HideInstance).HideInstance - # [pscustomobject] doesn't always work, unsure why. so return hashtable then turn it into pscustomobject on client + # [PSCustomObject] doesn't always work, unsure why. so return hashtable then turn it into PSCustomObject on client @{ ComputerName = $env:COMPUTERNAME InstanceName = $args[2] @@ -125,7 +125,7 @@ function Get-DbaHideInstance { try { $results = Invoke-Command2 -ComputerName $resolved.FullComputerName -Credential $Credential -ArgumentList $regRoot, $vsname, $instanceName -ScriptBlock $scriptBlock -ErrorAction Stop -Raw foreach ($result in $results) { - [pscustomobject]$result + [PSCustomObject]$result } } catch { Stop-Function -Message "Failed to connect to $($resolved.FullComputerName) using PowerShell remoting" -ErrorRecord $_ -Target $instance -Continue diff --git a/public/Get-DbaInstalledPatch.ps1 b/public/Get-DbaInstalledPatch.ps1 index 8bbc45a509..f8a65bf907 100644 --- a/public/Get-DbaInstalledPatch.ps1 +++ b/public/Get-DbaInstalledPatch.ps1 @@ -64,7 +64,7 @@ function Get-DbaInstalledPatch { } foreach ($patch in $patches) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $computer Name = $patch.DisplayName Version = $patch.DisplayVersion diff --git a/public/Get-DbaKbUpdate.ps1 b/public/Get-DbaKbUpdate.ps1 index f8e945a950..ec59e4ea5a 100644 --- a/public/Get-DbaKbUpdate.ps1 +++ b/public/Get-DbaKbUpdate.ps1 @@ -284,7 +284,7 @@ function Get-DbaKbUpdate { $properties = $properties | Where-Object { $PSItem -notin "LastModified", "Description", "Size", "Classification", "SupportedProducts", "MSRCNumber", "MSRCSeverity", "RebootBehavior", "RequestsUserInput", "ExclusiveInstall", "NetworkRequired", "UninstallNotes", "UninstallSteps", "SupersededBy", "Supersedes" } } - [pscustomobject]@{ + [PSCustomObject]@{ Title = $title NameLevel = $build.NameLevel SPLevel = $build.SPLevel @@ -320,4 +320,4 @@ function Get-DbaKbUpdate { } } } -} +} \ No newline at end of file diff --git a/public/Get-DbaLastGoodCheckDb.ps1 b/public/Get-DbaLastGoodCheckDb.ps1 index bbf2c25810..b7a48aa542 100644 --- a/public/Get-DbaLastGoodCheckDb.ps1 +++ b/public/Get-DbaLastGoodCheckDb.ps1 @@ -172,7 +172,7 @@ function Get-DbaLastGoodCheckDb { if ($lastKnownGood -isnot [datetime]) { $lastKnownGood = Get-Date '1/1/1900 12:00:00 AM' } - + $datecreated = $db.createDate if ($datecreated -isnot [datetime]) { $datecreated = Get-Date '1/1/1900 12:00:00 AM' diff --git a/public/Get-DbaMaintenanceSolutionLog.ps1 b/public/Get-DbaMaintenanceSolutionLog.ps1 index f33e842b3c..dcf67fcdb7 100644 --- a/public/Get-DbaMaintenanceSolutionLog.ps1 +++ b/public/Get-DbaMaintenanceSolutionLog.ps1 @@ -250,7 +250,7 @@ function Get-DbaMaintenanceSolutionLog { $remember['StartTime'] = [dbadatetime]([DateTime]::ParseExact($remember['Date and time'] , "yyyy-MM-dd HH:mm:ss", $null)) $remember.Remove('Date and time') $remember['Duration'] = ($remember['Duration'] -as [timespan]) - [pscustomobject]$remember + [PSCustomObject]$remember } $block = New-Object System.Collections.ArrayList } else { diff --git a/public/Get-DbaMaxMemory.ps1 b/public/Get-DbaMaxMemory.ps1 index c374df061a..3e84de01c3 100644 --- a/public/Get-DbaMaxMemory.ps1 +++ b/public/Get-DbaMaxMemory.ps1 @@ -72,7 +72,7 @@ function Get-DbaMaxMemory { $totalMemory = $totalMemory + 1 } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaMemoryUsage.ps1 b/public/Get-DbaMemoryUsage.ps1 index c8e539d264..850fb452f8 100644 --- a/public/Get-DbaMemoryUsage.ps1 +++ b/public/Get-DbaMemoryUsage.ps1 @@ -21,6 +21,41 @@ function Get-DbaMemoryUsage { For MFA support, please use Connect-DbaInstance. + .PARAMETER MemoryCounterRegex + Regular expression that is applied to the paths of the counters returned for the counter list set '*sql*:Memory Manager*' to display relevant Memory Manager counters. + + Default: '(Total Server Memory |Target Server Memory |Connection Memory |Lock Memory |SQL Cache Memory |Optimizer Memory |Granted Workspace Memory |Cursor memory usage|Maximum Workspace)' + + The default works for English language systems and has to be adapted for other languages. + + .PARAMETER PlanCounterRegex + Regular expression that is applied to the paths of the counters returned for the counter list set '*sql*:Plan Cache*' to display relevant Plan Cache counters. + + Default: '(cache pages|procedure plan|ad hoc sql plan|prepared SQL Plan)' + + The default works for English language systems and has to be adapted for other languages. + + .PARAMETER BufferCounterRegex + Regular expression that is applied to the paths of the counters returned for the counter list set '*Buffer Manager*' to display relevant Buffer Manager counters. + + Default: '(Free pages|Reserved pages|Stolen pages|Total pages|Database pages|target pages|extension .* pages)' + + The default works for English language systems and has to be adapted for other languages. + + .PARAMETER SSASCounterRegex + Regular expression that is applied to the paths of the counters returned for the counter list set 'MSAS*:Memory' to display relevant SSAS counters. + + Default: '(\\memory )' + + The default works for English language systems and has to be adapted for other languages. + + .PARAMETER SSISCounterRegex + Regular expression that is applied to the paths of the counters returned for the counter list set '*SSIS*' to display relevant SSIS counters. + + Default: '(memory)' + + The default works for English language systems and has to be adapted for other languages. + .PARAMETER EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. @@ -60,34 +95,27 @@ function Get-DbaMemoryUsage { [Alias("Host", "cn", "Server")] [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME, [PSCredential]$Credential, + [string]$MemoryCounterRegex = '(Total Server Memory |Target Server Memory |Connection Memory |Lock Memory |SQL Cache Memory |Optimizer Memory |Granted Workspace Memory |Cursor memory usage|Maximum Workspace)', + [string]$PlanCounterRegex = '(cache pages|procedure plan|ad hoc sql plan|prepared SQL Plan)', + [string]$BufferCounterRegex = '(Free pages|Reserved pages|Stolen pages|Total pages|Database pages|target pages|extension .* pages)', + [string]$SSASCounterRegex = '(\\memory )', + [string]$SSISCounterRegex = '(memory)', [switch]$EnableException ) begin { - if ($Simple) { - $Memcounters = '(Total Server Memory |Target Server Memory |Connection Memory |Lock Memory |SQL Cache Memory |Optimizer Memory |Granted Workspace Memory |Cursor memory usage|Maximum Workspace)' - $Plancounters = 'total\)\\cache pages' - $BufManpagecounters = 'Total pages' - $SSAScounters = '(\\memory usage)' - $SSIScounters = '(memory)' - } else { - $Memcounters = '(Total Server Memory |Target Server Memory |Connection Memory |Lock Memory |SQL Cache Memory |Optimizer Memory |Granted Workspace Memory |Cursor memory usage|Maximum Workspace)' - $Plancounters = '(cache pages|procedure plan|ad hoc sql plan|prepared SQL Plan)' - $BufManpagecounters = '(Free pages|Reserved pages|Stolen pages|Total pages|Database pages|target pages|extension .* pages)' - $SSAScounters = '(\\memory )' - $SSIScounters = '(memory)' - } - $scriptBlock = { - param ($Memcounters, - $Plancounters, - $BufManpagecounters, - $SSAScounters, - $SSIScounters) + param ( + $MemoryCounterRegex, + $PlanCounterRegex, + $BufferCounterRegex, + $SSASCounterRegex, + $SSISCounterRegex + ) <# DO NOT use Write-Message as this is inside of a script block #> Write-Verbose -Message "Searching for Memory Manager Counters on $Computer" try { - $availablecounters = (Get-Counter -ListSet '*sql*:Memory Manager*' -ErrorAction SilentlyContinue).paths - (Get-Counter -Counter $availablecounters -ErrorAction SilentlyContinue).countersamples | Where-Object { $_.Path -match $Memcounters } | ForEach-Object { + $availableCounters = (Get-Counter -ListSet '*sql*:Memory Manager*' -ErrorAction SilentlyContinue).paths + (Get-Counter -Counter $availableCounters -ErrorAction SilentlyContinue).countersamples | Where-Object { $_.Path -match $MemoryCounterRegex } | ForEach-Object { $instance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[0] if ($instance -eq 'sqlserver') { $instance = 'mssqlserver' } [PSCustomObject]@{ @@ -106,8 +134,8 @@ function Get-DbaMemoryUsage { <# DO NOT use Write-Message as this is inside of a script block #> Write-Verbose -Message "Searching for Plan Cache Counters on $Computer" try { - $availablecounters = (Get-Counter -ListSet '*sql*:Plan Cache*' -ErrorAction SilentlyContinue).paths - (Get-Counter -Counter $availablecounters -ErrorAction SilentlyContinue).countersamples | Where-Object { $_.Path -match $Plancounters } | ForEach-Object { + $availableCounters = (Get-Counter -ListSet '*sql*:Plan Cache*' -ErrorAction SilentlyContinue).paths + (Get-Counter -Counter $availableCounters -ErrorAction SilentlyContinue).countersamples | Where-Object { $_.Path -match $PlanCounterRegex } | ForEach-Object { $instance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[0] if ($instance -eq 'sqlserver') { $instance = 'mssqlserver' } [PSCustomObject]@{ @@ -126,8 +154,8 @@ function Get-DbaMemoryUsage { <# DO NOT use Write-Message as this is inside of a script block #> Write-Verbose -Message "Searching for Buffer Manager Counters on $Computer" try { - $availablecounters = (Get-Counter -ListSet "*Buffer Manager*" -ErrorAction SilentlyContinue).paths - (Get-Counter -Counter $availablecounters -ErrorAction SilentlyContinue).countersamples | Where-Object { $_.Path -match $BufManpagecounters } | ForEach-Object { + $availableCounters = (Get-Counter -ListSet "*Buffer Manager*" -ErrorAction SilentlyContinue).paths + (Get-Counter -Counter $availableCounters -ErrorAction SilentlyContinue).countersamples | Where-Object { $_.Path -match $BufferCounterRegex } | ForEach-Object { $instance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[0] if ($instance -eq 'sqlserver') { $instance = 'mssqlserver' } [PSCustomObject]@{ @@ -146,8 +174,8 @@ function Get-DbaMemoryUsage { <# DO NOT use Write-Message as this is inside of a script block #> Write-Verbose -Message "Searching for SSAS Counters on $Computer" try { - $availablecounters = (Get-Counter -ListSet "MSAS*:Memory" -ErrorAction SilentlyContinue).paths - (Get-Counter -Counter $availablecounters -ErrorAction SilentlyContinue).countersamples | Where-Object { $_.Path -match $SSAScounters } | ForEach-Object { + $availableCounters = (Get-Counter -ListSet "MSAS*:Memory" -ErrorAction SilentlyContinue).paths + (Get-Counter -Counter $availableCounters -ErrorAction SilentlyContinue).countersamples | Where-Object { $_.Path -match $SSASCounterRegex } | ForEach-Object { $instance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[0] if ($instance -eq 'sqlserver') { $instance = 'mssqlserver' } [PSCustomObject]@{ @@ -166,8 +194,8 @@ function Get-DbaMemoryUsage { <# DO NOT use Write-Message as this is inside of a script block #> Write-Verbose -Message "Searching for SSIS Counters on $Computer" try { - $availablecounters = (Get-Counter -ListSet "*SSIS*" -ErrorAction SilentlyContinue).paths - (Get-Counter -Counter $availablecounters -ErrorAction SilentlyContinue).countersamples | Where-Object { $_.Path -match $SSIScounters } | ForEach-Object { + $availableCounters = (Get-Counter -ListSet "*SSIS*" -ErrorAction SilentlyContinue).paths + (Get-Counter -Counter $availableCounters -ErrorAction SilentlyContinue).countersamples | Where-Object { $_.Path -match $SSISCounterRegex } | ForEach-Object { $instance = (($_.Path.split("\")[-2]).replace("mssql`$", "")).split(':')[0] if ($instance -eq 'sqlserver') { $instance = 'mssqlserver' } [PSCustomObject]@{ @@ -191,7 +219,7 @@ function Get-DbaMemoryUsage { if ($reply.FullComputerName) { $Computer = $reply.FullComputerName try { - foreach ($result in (Invoke-Command2 -ComputerName $Computer -Credential $Credential -ScriptBlock $scriptBlock -argumentlist $Memcounters, $Plancounters, $BufManpagecounters, $SSAScounters, $SSIScounters)) { + foreach ($result in (Invoke-Command2 -ComputerName $Computer -Credential $Credential -ScriptBlock $scriptBlock -argumentlist $MemoryCounterRegex, $PlanCounterRegex, $BufferCounterRegex, $SSASCounterRegex, $SSISCounterRegex)) { [PSCustomObject]@{ ComputerName = $result.ComputerName SqlInstance = $result.SqlInstance diff --git a/public/Get-DbaMsdtc.ps1 b/public/Get-DbaMsdtc.ps1 index 9d58b0a67f..10f611fc53 100644 --- a/public/Get-DbaMsdtc.ps1 +++ b/public/Get-DbaMsdtc.ps1 @@ -58,7 +58,7 @@ function Get-DbaMsdtc { [Parameter(ValueFromPipeline)] [Alias('cn', 'host', 'Server')] [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME, - [pscredential]$Credential, + [PSCredential]$Credential, [switch]$EnableException ) diff --git a/public/Get-DbaNetworkConfiguration.ps1 b/public/Get-DbaNetworkConfiguration.ps1 index 4193e8bba3..1aa0128ee0 100644 --- a/public/Get-DbaNetworkConfiguration.ps1 +++ b/public/Get-DbaNetworkConfiguration.ps1 @@ -290,4 +290,4 @@ function Get-DbaNetworkConfiguration { } } } -} +} \ No newline at end of file diff --git a/public/Get-DbaPermission.ps1 b/public/Get-DbaPermission.ps1 index 17b864c416..aa49620271 100644 --- a/public/Get-DbaPermission.ps1 +++ b/public/Get-DbaPermission.ps1 @@ -218,36 +218,36 @@ function Get-DbaPermission { AND dp.is_fixed_role=1 UNION ALL -- include the dbo user SELECT - [ComputerName] = SERVERPROPERTY('MachineName') - , [InstanceName] = ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') - , [SqlInstance] = SERVERPROPERTY('ServerName') - , [database] = DB_NAME() - , [PermState] = '' - , [PermissionName] = 'CONTROL' - , [SecurableType] = 'DATABASE' - , [Securable] = DB_NAME() - , [Grantee] = SUSER_SNAME(owner_sid) - , [GranteeType] = 'DATABASE OWNER (dbo user)' - , [revokestatement] = '' - , [grantstatement] = '' + [ComputerName] = SERVERPROPERTY('MachineName') + , [InstanceName] = ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') + , [SqlInstance] = SERVERPROPERTY('ServerName') + , [database] = DB_NAME() + , [PermState] = '' + , [PermissionName] = 'CONTROL' + , [SecurableType] = 'DATABASE' + , [Securable] = DB_NAME() + , [Grantee] = SUSER_SNAME(owner_sid) + , [GranteeType] = 'DATABASE OWNER (dbo user)' + , [revokestatement] = '' + , [grantstatement] = '' FROM sys.databases WHERE name = DB_NAME() UNION ALL -- include the users with the db_owner role SELECT - [ComputerName] = SERVERPROPERTY('MachineName') - , [InstanceName] = ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') - , [SqlInstance] = SERVERPROPERTY('ServerName') - , [database] = DB_NAME() - , [PermState] = '' - , [PermissionName] = 'CONTROL' - , [SecurableType] = 'DATABASE' - , [Securable] = DB_NAME() - , [Grantee] = databaseUser.name - , [GranteeType] = 'DATABASE OWNER (db_owner role)' - , [revokestatement] = '' - , [grantstatement] = '' + [ComputerName] = SERVERPROPERTY('MachineName') + , [InstanceName] = ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') + , [SqlInstance] = SERVERPROPERTY('ServerName') + , [database] = DB_NAME() + , [PermState] = '' + , [PermissionName] = 'CONTROL' + , [SecurableType] = 'DATABASE' + , [Securable] = DB_NAME() + , [Grantee] = databaseUser.name + , [GranteeType] = 'DATABASE OWNER (db_owner role)' + , [revokestatement] = '' + , [grantstatement] = '' FROM ( SELECT @@ -266,18 +266,18 @@ function Get-DbaPermission { databaseUser.name <> 'dbo' UNION ALL -- include the schema owners SELECT - [ComputerName] = SERVERPROPERTY('MachineName') - , [InstanceName] = ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') - , [SqlInstance] = SERVERPROPERTY('ServerName') - , [database] = DB_NAME() - , [PermState] = '' - , [PermissionName] = 'CONTROL' - , [SecurableType] = 'SCHEMA' - , [Securable] = name - , [Grantee] = USER_NAME(principal_id) - , [GranteeType] = 'SCHEMA OWNER' - , [revokestatement] = '' - , [grantstatement] = '' + [ComputerName] = SERVERPROPERTY('MachineName') + , [InstanceName] = ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') + , [SqlInstance] = SERVERPROPERTY('ServerName') + , [database] = DB_NAME() + , [PermState] = '' + , [PermissionName] = 'CONTROL' + , [SecurableType] = 'SCHEMA' + , [Securable] = name + , [Grantee] = USER_NAME(principal_id) + , [GranteeType] = 'SCHEMA OWNER' + , [revokestatement] = '' + , [grantstatement] = '' FROM sys.schemas WHERE @@ -326,4 +326,4 @@ function Get-DbaPermission { } } } -} +} \ No newline at end of file diff --git a/public/Get-DbaPfDataCollector.ps1 b/public/Get-DbaPfDataCollector.ps1 index 72c1e85d76..476f9e07d9 100644 --- a/public/Get-DbaPfDataCollector.ps1 +++ b/public/Get-DbaPfDataCollector.ps1 @@ -110,7 +110,7 @@ function Get-DbaPfDataCollector { $remote = $null } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $set.ComputerName DataCollectorSet = $set.Name Name = $col.Name diff --git a/public/Get-DbaPfDataCollectorCounter.ps1 b/public/Get-DbaPfDataCollectorCounter.ps1 index 61f235e545..4dfb35fd2e 100644 --- a/public/Get-DbaPfDataCollectorCounter.ps1 +++ b/public/Get-DbaPfDataCollectorCounter.ps1 @@ -108,7 +108,7 @@ function Get-DbaPfDataCollectorCounter { foreach ($counterobject in $InputObject) { foreach ($countername in $counterobject.Counters) { if ($Counter -and $Counter -notcontains $countername) { continue } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $counterobject.ComputerName DataCollectorSet = $counterobject.DataCollectorSet DataCollector = $counterobject.Name diff --git a/public/Get-DbaPfDataCollectorCounterSample.ps1 b/public/Get-DbaPfDataCollectorCounterSample.ps1 index 5fcadf98fd..cc8a978348 100644 --- a/public/Get-DbaPfDataCollectorCounterSample.ps1 +++ b/public/Get-DbaPfDataCollectorCounterSample.ps1 @@ -169,7 +169,7 @@ function Get-DbaPfDataCollectorCounterSample { foreach ($pscounter in $pscounters) { foreach ($sample in $pscounter.CounterSamples) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $counterobject.ComputerName DataCollectorSet = $counterobject.DataCollectorSet DataCollector = $counterobject.DataCollector diff --git a/public/Get-DbaPfDataCollectorSet.ps1 b/public/Get-DbaPfDataCollectorSet.ps1 index 9544223091..55c6563ba9 100644 --- a/public/Get-DbaPfDataCollectorSet.ps1 +++ b/public/Get-DbaPfDataCollectorSet.ps1 @@ -124,7 +124,7 @@ function Get-DbaPfDataCollectorSet { $remote = $null } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME Name = $setname LatestOutputLocation = $set.LatestOutputLocation diff --git a/public/Get-DbaPfDataCollectorSetTemplate.ps1 b/public/Get-DbaPfDataCollectorSetTemplate.ps1 index a67b23a621..1b187e81e1 100644 --- a/public/Get-DbaPfDataCollectorSetTemplate.ps1 +++ b/public/Get-DbaPfDataCollectorSetTemplate.ps1 @@ -83,7 +83,7 @@ function Get-DbaPfDataCollectorSetTemplate { ($dataset.Name -match $Pattern) -or ($dataset.Description -match $Pattern) ) { - [pscustomobject]@{ + [PSCustomObject]@{ Name = $dataset.name Source = $meta.Source UserAccount = $dataset.useraccount @@ -93,7 +93,7 @@ function Get-DbaPfDataCollectorSetTemplate { } | Select-DefaultView -ExcludeProperty File, Path } } else { - [pscustomobject]@{ + [PSCustomObject]@{ Name = $dataset.name Source = $meta.Source UserAccount = $dataset.useraccount diff --git a/public/Get-DbaProductKey.ps1 b/public/Get-DbaProductKey.ps1 index 2736377a0b..b80c4a6a27 100644 --- a/public/Get-DbaProductKey.ps1 +++ b/public/Get-DbaProductKey.ps1 @@ -149,7 +149,7 @@ function Get-DbaProductKey { $sqlkey = "SQL Server Express Edition" } - [pscustomobject]@{ + [PSCustomObject]@{ Key = $sqlkey } $reg.Close() @@ -182,10 +182,10 @@ function Get-DbaProductKey { try { $results = Invoke-Command2 -ComputerName $computer.ComputerName -Credential $Credential -ScriptBlock $scriptBlock -ArgumentList $server.VersionMajor, $instanceReg, $server.Edition } catch { - Stop-Function -Message "Failure" -ErrorRecord $_ + Stop-Function -Message "Failure" -ErrorRecord $_ -Continue } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaRandomizedValue.ps1 b/public/Get-DbaRandomizedValue.ps1 index 3d878d8382..15ff83d344 100644 --- a/public/Get-DbaRandomizedValue.ps1 +++ b/public/Get-DbaRandomizedValue.ps1 @@ -189,7 +189,7 @@ function Get-DbaRandomizedValue { if (Test-FunctionInterrupt) { return } - if ($DataType) { + if ($DataType -and -not $RandomizerSubType) { switch ($DataType.ToLowerInvariant()) { 'bigint' { @@ -206,7 +206,7 @@ function Get-DbaRandomizedValue { $script:faker.Random.Long($Min, $Max) } - { $psitem -in 'bit', 'bool' } { + { $PSItem -in 'bit', 'bool' } { if ($script:faker.Random.Bool()) { 1 } else { @@ -234,7 +234,7 @@ function Get-DbaRandomizedValue { ($script:faker.Date.Past()).ToString("yyyy-MM-dd HH:mm:ss.fffffff", [System.Globalization.CultureInfo]::InvariantCulture) } } - { $psitem -in 'decimal', 'float', 'money', 'numeric', 'real' } { + { $PSItem -in 'decimal', 'float', 'money', 'numeric', 'real' } { $script:faker.Finance.Amount($Min, $Max, $Precision) } 'int' { @@ -287,7 +287,7 @@ function Get-DbaRandomizedValue { $script:faker.Random.Int($Min, $Max) } - { $psitem -in 'uniqueidentifier', 'guid' } { + { $PSItem -in 'uniqueidentifier', 'guid' } { $script:faker.System.Random.Guid().Guid } 'userdefineddatatype' { @@ -301,7 +301,7 @@ function Get-DbaRandomizedValue { $null } } - { $psitem -in 'char', 'nchar', 'nvarchar', 'varchar' } { + { $PSItem -in 'char', 'nchar', 'nvarchar', 'varchar' } { $script:faker.Random.String2($Min, $Max, $CharacterString) } @@ -346,6 +346,14 @@ function Get-DbaRandomizedValue { $script:faker.Database.$RandomizerSubType() } 'date' { + if ($DataType -eq 'date') { + $formatString = "yyyy-MM-dd" + } elseif ($DataType -eq 'datetime') { + $formatString = "yyyy-MM-dd HH:mm:ss.fff" + } elseif ($DataType -eq 'datetime2') { + $formatString = "yyyy-MM-dd HH:mm:ss.fffffff" + } + if ($randSubType -eq 'between') { if (-not $Min) { @@ -359,7 +367,7 @@ function Get-DbaRandomizedValue { if ($Min -gt $Max) { Stop-Function -Message "The minimum value for the date cannot be later than maximum value" -Continue -Target $Min } else { - ($script:faker.Date.Between($Min, $Max)).ToString("yyyy-MM-dd HH:mm:ss.fffffff", [System.Globalization.CultureInfo]::InvariantCulture) + ($script:faker.Date.Between($Min, $Max)).ToString($formatString, [System.Globalization.CultureInfo]::InvariantCulture) } } elseif ($randSubType -eq 'past') { if ($Max) { @@ -369,9 +377,9 @@ function Get-DbaRandomizedValue { $yearsToGoBack = 1 } - $script:faker.Date.Past($yearsToGoBack, $Max).ToString("yyyy-MM-dd HH:mm:ss.fffffff", [System.Globalization.CultureInfo]::InvariantCulture) + $script:faker.Date.Past($yearsToGoBack, $Max).ToString($formatString, [System.Globalization.CultureInfo]::InvariantCulture) } else { - $script:faker.Date.Past().ToString("yyyy-MM-dd HH:mm:ss.fffffff", [System.Globalization.CultureInfo]::InvariantCulture) + $script:faker.Date.Past().ToString($formatString, [System.Globalization.CultureInfo]::InvariantCulture) } } elseif ($randSubType -eq 'future') { if ($Min) { @@ -381,13 +389,12 @@ function Get-DbaRandomizedValue { $yearsToGoForward = 1 } - $script:faker.Date.Future($yearsToGoForward, $Min).ToString("yyyy-MM-dd HH:mm:ss.fffffff", [System.Globalization.CultureInfo]::InvariantCulture) + $script:faker.Date.Future($yearsToGoForward, $Min).ToString($formatString, [System.Globalization.CultureInfo]::InvariantCulture) } else { - $script:faker.Date.Future().ToString("yyyy-MM-dd HH:mm:ss.fffffff", [System.Globalization.CultureInfo]::InvariantCulture) + $script:faker.Date.Future().ToString($formatString, [System.Globalization.CultureInfo]::InvariantCulture) } - } elseif ($randSubType -eq 'recent') { - $script:faker.Date.Recent().ToString("yyyy-MM-dd HH:mm:ss.fffffff", [System.Globalization.CultureInfo]::InvariantCulture) + $script:faker.Date.Recent().ToString($formatString, [System.Globalization.CultureInfo]::InvariantCulture) } elseif ($randSubType -eq 'random') { if ($Min -or $Max) { if (-not $Min) { @@ -398,9 +405,9 @@ function Get-DbaRandomizedValue { $Max = (Get-Date).AddYears(1) } - ($script:faker.Date.Between($Min, $Max)).ToString("yyyy-MM-dd HH:mm:ss.fffffff", [System.Globalization.CultureInfo]::InvariantCulture) + ($script:faker.Date.Between($Min, $Max)).ToString($formatString, [System.Globalization.CultureInfo]::InvariantCulture) } else { - ($script:faker.Date.Past()).ToString("yyyy-MM-dd HH:mm:ss.fffffff", [System.Globalization.CultureInfo]::InvariantCulture) + ($script:faker.Date.Past()).ToString($formatString, [System.Globalization.CultureInfo]::InvariantCulture) } } else { $script:faker.Date.$RandomizerSubType() diff --git a/public/Get-DbaRegServer.ps1 b/public/Get-DbaRegServer.ps1 index 5b9b36fe07..5ff607e1fd 100644 --- a/public/Get-DbaRegServer.ps1 +++ b/public/Get-DbaRegServer.ps1 @@ -174,7 +174,7 @@ function Get-DbaRegServer { $tempgroup.Description = $azuregroup.Description foreach ($server in ($store.AzureDataStudioConnectionStore.Connections | Where-Object GroupId -eq $azuregroup.Id)) { - $azureids += [pscustomobject]@{ id = $server.Id; group = $groupname } + $azureids += [PSCustomObject]@{ id = $server.Id; group = $groupname } $connname = $server.Options['connectionName'] if (-not $connname) { $connname = $server.Options['server'] diff --git a/public/Get-DbaRepPublication.ps1 b/public/Get-DbaRepPublication.ps1 deleted file mode 100644 index 8a04b05640..0000000000 --- a/public/Get-DbaRepPublication.ps1 +++ /dev/null @@ -1,120 +0,0 @@ -function Get-DbaRepPublication { - <# - .SYNOPSIS - Displays all publications for a server or database. - - .DESCRIPTION - Quickly find all transactional, merge, and snapshot publications on a specific server or database. - - All replication commands need SQL Server Management Studio installed and are therefore currently not supported. - Have a look at this issue to get more information: https://github.com/dataplat/dbatools/issues/7428 - - .PARAMETER SqlInstance - The target SQL Server instance or instances. - - .PARAMETER Database - The database(s) to process. If unspecified, all databases will be processed. - - .PARAMETER SqlCredential - Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). - - Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. - - For MFA support, please use Connect-DbaInstance. - - .PARAMETER PublicationType - Limit by specific type of publication. Valid choices include: Transactional, Merge, Snapshot - - .PARAMETER EnableException - byng this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. - - .NOTES - Tags: Replication - Author: Colin Douglas - - Website: https://dbatools.io - Copyright: (c) 2018 by dbatools, licensed under MIT - License: MIT https://opensource.org/licenses/MIT - - .LINK - https://dbatools.io/Get-DbaRepPublication - - .EXAMPLE - PS C:\> Get-DbaRepPublication -SqlInstance sql2008, sqlserver2012 - - Return all publications for servers sql2008 and sqlserver2012. - - .EXAMPLE - PS C:\> Get-DbaRepPublication -SqlInstance sql2008 -Database TestDB - - Return all publications on server sql2008 for only the TestDB database - - .EXAMPLE - PS C:\> Get-DbaRepPublication -SqlInstance sql2008 -PublicationType Transactional - - Return all publications on server sql2008 for all databases that have Transactional publications - - #> - [CmdletBinding()] - param ( - [parameter(Mandatory, ValueFromPipeline)] - [DbaInstanceParameter[]]$SqlInstance, - [object[]]$Database, - [PSCredential]$SqlCredential, - [ValidateSet("Transactional", "Merge", "Snapshot")] - [object[]]$PublicationType, - [switch]$EnableException - ) - begin { - Add-ReplicationLibrary - } - process { - if (Test-FunctionInterrupt) { return } - foreach ($instance in $SqlInstance) { - - # Connect to Publisher - try { - $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9 - } catch { - Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue - } - - $dbList = $server.Databases - - if ($Database) { - $dbList = $dbList | Where-Object name -in $Database - } - - $dbList = $dbList | Where-Object { ($_.ID -gt 4) -and ($_.status -ne "Offline") } - - - foreach ($db in $dbList) { - - if (($db.ReplicationOptions -ne "Published") -and ($db.ReplicationOptions -ne "MergePublished")) { - Write-Message -Level Verbose -Message "Skipping $($db.name). Database is not published." - } - - $repDB = Connect-ReplicationDB -Server $server -Database $db - - $pubTypes = $repDB.TransPublications + $repDB.MergePublications - - if ($PublicationType) { - $pubTypes = $pubTypes | Where-Object Type -in $PublicationType - } - - foreach ($pub in $pubTypes) { - - [PSCustomObject]@{ - ComputerName = $server.ComputerName - InstanceName = $server.InstanceName - SqlInstance = $server.SqlInstance - Server = $server.name - Database = $db.name - PublicationName = $pub.Name - PublicationType = $pub.Type - } - } - } - } - } -} \ No newline at end of file diff --git a/public/Get-DbaReplArticle.ps1 b/public/Get-DbaReplArticle.ps1 new file mode 100644 index 0000000000..21da21b046 --- /dev/null +++ b/public/Get-DbaReplArticle.ps1 @@ -0,0 +1,140 @@ +function Get-DbaReplArticle { + <# + .SYNOPSIS + Gets the information about publication articles. + + .DESCRIPTION + This function locates and enumerates articles' information. + + Can specify a database, publication or article name. + + .PARAMETER SqlInstance + The target SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER Database + Specifies one or more database(s) to process. If unspecified, all databases will be processed. + + .PARAMETER Publication + Specifies one or more publication(s) to process. If unspecified, all publications will be processed. + + .PARAMETER Schema + Specifies one or more schema(s) to process. If unspecified, all schemas will be processed. + + .PARAMETER Name + Specify the name of one or more article(s) to process. If unspecified, all articles will be processed. + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .NOTES + Tags: repl, Replication + Author: Cláudio Silva (@claudioessilva), claudioessilva.eu + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/Get-DbaReplArticle + + .EXAMPLE + PS C:\> Get-DbaReplArticle -SqlInstance mssql1 + + Retrieve information of all articles from all publications on all databases for server mssql1. + + .EXAMPLE + PS C:\> Get-DbaReplArticle -SqlInstance mssql1 -Database pubs + + Retrieve information of all articles from all publications on 'pubs' database for server mssql1. + + .EXAMPLE + PS C:\> Get-DbaReplArticle -SqlInstance mssql1 -Database pubs -Publication PubName + + Retrieve information of all articles from 'PubName' on 'pubs' database for server mssql1. + + .EXAMPLE + PS C:\> Get-DbaReplArticle -SqlInstance mssql1 -Database pubs -Schema sales + + Retrieve information of articles in the 'sales' schema on 'pubs' database for server mssql1. + + .EXAMPLE + PS C:\> Get-DbaReplArticle -SqlInstance mssql1 -Database pubs -Publication PubName -Name sales + + Retrieve information of 'sales' article from 'PubName' on 'pubs' database for server mssql1. + + #> + [CmdletBinding()] + param ( + [parameter(ValueFromPipeline)] + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [object[]]$Database, + [object[]]$Publication, + [string[]]$Schema, + [string[]]$Name, + [switch]$EnableException + ) + begin { + Add-ReplicationLibrary + } + process { + if (Test-FunctionInterrupt) { return } + + foreach ($instance in $SqlInstance) { + try { + $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential + } catch { + Stop-Function -Message "Error occurred while establishing connection to $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue + } + + try { + $databases = $server.Databases | Where-Object IsAccessible -eq $true + if ($Database) { + $databases = $databases | Where-Object Name -in $Database + } + } catch { + Stop-Function -Message "Error occurred while getting databases from $instance" -ErrorRecord $_ -Target $instance -Continue + } + + try { + foreach ($db in $databases) { + Write-Message -Level Verbose -Message ('Working on {0}' -f $db.Name) + + $publications = Get-DbaReplPublication -SqlInstance $server -Database $db.Name -EnableException:$EnableException + + if ($Publication) { + $publications = $publications | Where-Object Name -in $Publication + } + + $articles = $publications.Articles + + if ($Schema) { + $articles = $articles | Where-Object SourceObjectOwner -in $Schema + } + if ($Name) { + $articles = $articles | Where-Object Name -in $Name + } + + foreach ($art in $articles) { + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name SqlInstance -Value $server + + Select-DefaultView -InputObject $art -Property ComputerName, InstanceName, SqlInstance, DatabaseName, PublicationName, Name, Type, VerticalPartition, SourceObjectOwner, SourceObjectName #, DestinationObjectOwner, DestinationObjectName + } + } + } catch { + Stop-Function -Message "Error occurred while getting articles from $instance" -ErrorRecord $_ -Target $instance -Continue + } + } + } +} \ No newline at end of file diff --git a/public/Get-DbaReplArticleColumn.ps1 b/public/Get-DbaReplArticleColumn.ps1 new file mode 100644 index 0000000000..9f2814ee6e --- /dev/null +++ b/public/Get-DbaReplArticleColumn.ps1 @@ -0,0 +1,122 @@ +function Get-DbaReplArticleColumn { + <# + .SYNOPSIS + Gets the information about replicated article columns. + + .DESCRIPTION + This function enumerates column information for given articles. + + .PARAMETER SqlInstance + The target SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER Database + Specifies one or more database(s) to process. If unspecified, all databases will be processed. + + .PARAMETER Publication + Specifies one or more publication(s) to process. If unspecified, all publications will be processed. + + .PARAMETER Article + Specifies one or more article(s) to process. If unspecified, all articles will be processed. + + .PARAMETER Column + Specifies one or more column(s) to process. If unspecified, all columns will be processed. + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .NOTES + Tags: repl, Replication + Author: Cláudio Silva (@claudioessilva), claudioessilva.eu + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/Get-DbaReplArticleColumn + + .EXAMPLE + PS C:\> Get-DbaReplArticleColumn -SqlInstance sqlserver2019 + + Retrieve information of all replicated columns in any publications on server sqlserver2019. + + .EXAMPLE + PS C:\> Get-DbaReplArticleColumn -SqlInstance sqlserver2019 -Database pubs + + Retrieve information of all replicated columns in any publications from the pubs database on server sqlserver2019. + + .EXAMPLE + PS C:\> Get-DbaReplArticleColumn -SqlInstance sqlserver2019 -Publication test + + Retrieve information of all replicated columns in the test publication on server sqlserver2019. + + .EXAMPLE + PS C:\> Get-DbaReplArticleColumn -SqlInstance sqlserver2019 -Database pubs -Publication PubName -Article sales + + Retrieve information of 'sales' article from 'PubName' on 'pubs' database for server sqlserver2019. + + .EXAMPLE + PS C:\> Get-DbaReplArticleColumn -SqlInstance sqlserver2019 -Column state + + Retrieve information for the state column in any publication from any database on server sqlserver2019. + + #> + [CmdletBinding()] + param ( + [parameter(ValueFromPipeline)] + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [object[]]$Database, + [parameter(ValueFromPipeline)] + [object[]]$Publication, + [string[]]$Article, + [string[]]$Column, + [switch]$EnableException + ) + process { + if (Test-FunctionInterrupt) { return } + + $articles = Get-DbaReplArticle -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Database $Database -Publication $Publication -Name $Article -EnableException:$EnableException + + foreach ($art in $articles) { + try { + + $columns = $art.ListReplicatedColumns() + + if ($Column) { + $columns = $columns | Where-Object { $_ -In $Column } + } + + foreach ($col in $columns) { + + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name ComputerName -Value $art.ComputerName + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name InstanceName -Value $art.InstanceName + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name SqlInstance -Value $art.SqlInstance + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name DatabaseName -Value $art.DatabaseName + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name PublicationName -Value $art.PublicationName + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name ArticleName -Value $art.Name + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name ArticleId -Value $art.ArticleId + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name Description -Value $art.Description + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name Type -Value $art.Type + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name VerticalPartition -Value $art.VerticalPartition + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name SourceObjectOwner -Value $art.SourceObjectOwner + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name SourceObjectName -Value $art.SourceObjectName + Add-Member -Force -InputObject $art -MemberType NoteProperty -Name ColumnName -Value $col + + Select-DefaultView -InputObject $art -Property ComputerName, InstanceName, SqlInstance, DatabaseName, PublicationName, ArticleName, ArticleId, ColumnName #, DestinationObjectOwner, DestinationObjectName + } + } catch { + Stop-Function -Message "Error occurred while getting article columns from $instance" -ErrorRecord $_ -Target $instance -Continue + } + } + } +} \ No newline at end of file diff --git a/public/Get-DbaRepDistributor.ps1 b/public/Get-DbaReplDistributor.ps1 similarity index 63% rename from public/Get-DbaRepDistributor.ps1 rename to public/Get-DbaReplDistributor.ps1 index c5657c688e..16f1fd9a96 100644 --- a/public/Get-DbaRepDistributor.ps1 +++ b/public/Get-DbaReplDistributor.ps1 @@ -1,4 +1,4 @@ -function Get-DbaRepDistributor { +function Get-DbaReplDistributor { <# .SYNOPSIS Gets the information about a replication distributor for a given SQL Server instance. @@ -6,9 +6,6 @@ function Get-DbaRepDistributor { .DESCRIPTION This function locates and enumerates distributor information for a given SQL Server instance. - All replication commands need SQL Server Management Studio installed and are therefore currently not supported. - Have a look at this issue to get more information: https://github.com/dataplat/dbatools/issues/7428 - .PARAMETER SqlInstance The target SQL Server instance or instances. @@ -33,13 +30,17 @@ function Get-DbaRepDistributor { License: MIT https://opensource.org/licenses/MIT .LINK - https://dbatools.io/Get-DbaRepDistributor + https://dbatools.io/Get-DbaReplDistributor .EXAMPLE - PS C:\> Get-DbaRepDistributor -SqlInstance sql2008, sqlserver2012 + PS C:\> Get-DbaReplDistributor -SqlInstance sql2008, sqlserver2012 Retrieve distributor information for servers sql2008 and sqlserver2012. + .EXAMPLE + PS C:\> Connect-DbaInstance -SqlInstance mssql1 | Get-DbaReplDistributor + + Pipe a SQL Server instance to Get-DbaReplDistributor to retrieve distributor information. #> [CmdletBinding()] param ( @@ -48,9 +49,6 @@ function Get-DbaRepDistributor { [PSCredential]$SqlCredential, [switch]$EnableException ) - begin { - Add-ReplicationLibrary - } process { if (Test-FunctionInterrupt) { return } foreach ($instance in $SqlInstance) { @@ -58,17 +56,11 @@ function Get-DbaRepDistributor { # Connect to the distributor of the instance try { - $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential - $sqlconn = New-SqlConnection -SqlInstance $instance -SqlCredential $SqlCredential - - $distributor = New-Object Microsoft.SqlServer.Replication.ReplicationServer $sqlconn + $distributor = Get-DbaReplServer -SqlInstance $instance -SqlCredential $SqlCredential -EnableException:$EnableException } catch { - Stop-Function -Message "Error occurred while establishing connection to $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue + Stop-Function -Message "Error occurred getting information about $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue } - - Add-Member -Force -InputObject $distributor -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName - Add-Member -Force -InputObject $distributor -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName - Add-Member -Force -InputObject $distributor -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName + Write-Message -Level Verbose -Message "Getting publisher for $server" Select-DefaultView -InputObject $distributor -Property ComputerName, InstanceName, SqlInstance, IsPublisher, IsDistributor, DistributionServer, DistributionDatabase, DistributorInstalled, DistributorAvailable, HasRemotePublisher } diff --git a/public/Get-DbaReplPublication.ps1 b/public/Get-DbaReplPublication.ps1 new file mode 100644 index 0000000000..434c444a62 --- /dev/null +++ b/public/Get-DbaReplPublication.ps1 @@ -0,0 +1,152 @@ +function Get-DbaReplPublication { + <# + .SYNOPSIS + Displays all publications on a server. + + .DESCRIPTION + Quickly find all transactional, merge, and snapshot publications on a server or filter by database, name or type. + + .PARAMETER SqlInstance + The target SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER Database + The database(s) to process. If unspecified, all databases will be processed. + + .PARAMETER Name + The name of the publication. + + .PARAMETER Type + Limit by specific type of publication. Valid choices include: Transactional, Merge, Snapshot. + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .NOTES + Tags: repl, Replication + Author: Colin Douglas + + Website: https://dbatools.io + Copyright: (c) 2018 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/Get-DbaReplPublication + + .EXAMPLE + PS C:\> Get-DbaReplPublication -SqlInstance sql2008, sqlserver2012 + + Return all publications for servers sql2008 and sqlserver2012. + + .EXAMPLE + PS C:\> Get-DbaReplPublication -SqlInstance sql2008 -Database TestDB + + Return all publications on server sql2008 for only the TestDB database + + .EXAMPLE + PS C:\> Get-DbaReplPublication -SqlInstance sql2008 -Type Transactional + + Return all transactional publications on server sql2008. + + .EXAMPLE + PS C:\> Get-DbaReplPublication -SqlInstance mssql1 -Name Mergey + + Returns the Mergey publications on server mssql1 + + .EXAMPLE + PS C:\> Connect-DbaInstance -SqlInstance mssql1 | Get-DbaReplPublication + + Returns all publications on server mssql1 using the pipeline. + #> + [CmdletBinding()] + param ( + [parameter(Mandatory, ValueFromPipeline)] + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [object[]]$Database, + [String]$Name, + [Alias("PublicationType")] + [ValidateSet("Transactional", "Merge", "Snapshot")] + [object[]]$Type, + [switch]$EnableException + ) + begin { + Add-ReplicationLibrary + } + process { + if (Test-FunctionInterrupt) { return } + foreach ($instance in $SqlInstance) { + # Connect to Publisher + try { + $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 9 + } catch { + Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue + } + + try { + $databases = $server.Databases | Where-Object { $_.IsAccessible -eq $true -and (-not $_.IsSystemObject) } + if ($Database) { + $databases = $databases | Where-Object Name -In $Database + } + } catch { + Stop-Function -Message "Unable to get databases for" -ErrorRecord $_ -Target $server -Continue + } + + try { + foreach ($db in $databases) { + + #test if the database published + if ((($db.ReplicationOptions -band [Microsoft.SqlServer.Management.Smo.ReplicationOptions]::Published) -ne [Microsoft.SqlServer.Management.Smo.ReplicationOptions]::Published) -and + (($db.ReplicationOptions -band [Microsoft.SqlServer.Management.Smo.ReplicationOptions]::MergePublished) -ne [Microsoft.SqlServer.Management.Smo.ReplicationOptions]::MergePublished)) { + # The database is not published + Write-Message -Level Verbose -Message "Skipping $($db.name). Database is not published." + continue + } + + + $repDB = Connect-ReplicationDB -Server $server -Database $db -EnableException:$EnableException + + $pubTypes = $repDB.TransPublications + $repDB.MergePublications + + if ($Type) { + $pubTypes = $pubTypes | Where-Object Type -in $Type + } + + if ($Name) { + $pubTypes = $pubTypes | Where-Object Name -in $Name + } + + foreach ($pub in $pubTypes) { + if ($pub.Type -eq 'Merge') { + $articles = $pub.MergeArticles + $subscriptions = $pub.MergeSubscriptions + } else { + $articles = $pub.TransArticles + $subscriptions = $pub.TransSubscriptions + } + + + Add-Member -Force -InputObject $pub -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName + Add-Member -Force -InputObject $pub -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName + Add-Member -Force -InputObject $pub -MemberType NoteProperty -Name SQLInstance -Value $server + Add-Member -Force -InputObject $pub -MemberType NoteProperty -Name Articles -Value $articles + Add-Member -Force -InputObject $pub -MemberType NoteProperty -Name Subscriptions -Value $subscriptions + + Select-DefaultView -InputObject $pub -Property ComputerName, InstanceName, SQLInstance, DatabaseName, Name, Type, Articles, Subscriptions + + } + } + } catch { + Stop-Function -Message "Unable to get publications from " -ErrorRecord $_ -Target $server -Continue + } + } + } +} \ No newline at end of file diff --git a/public/Get-DbaReplPublisher.ps1 b/public/Get-DbaReplPublisher.ps1 new file mode 100644 index 0000000000..3db1b106af --- /dev/null +++ b/public/Get-DbaReplPublisher.ps1 @@ -0,0 +1,79 @@ +function Get-DbaReplPublisher { + <# + .SYNOPSIS + Gets publisher information for the target SQL instances. + + .DESCRIPTION + Gets publisher information for the target SQL instances. + + .PARAMETER SqlInstance + The target SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .NOTES + Tags: repl, Replication + Author: Mikey Bronowski (@MikeyBronowski), bronowski.it + + Website: https://dbatools.io + Copyright: (c) 2022 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/Get-DbaReplPublisher + + .EXAMPLE + PS C:\> Get-DbaReplPublisher -SqlInstance mssql1 + + Gets publisher for the mssql1 instance. + + .EXAMPLE + PS C:\> Connect-DbaInstance -SqlInstance mssql1 | Get-DbaReplPublisher + + Pipes a SQL Server object to get publisher information for the mssql1 instance. + #> + [CmdletBinding()] + param ( + [parameter(Mandatory, ValueFromPipeline)] + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [switch]$EnableException + ) + process { + foreach ($instance in $SqlInstance) { + try { + $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential + $replServer = Get-DbaReplServer -SqlInstance $server -EnableException:$EnableException + } catch { + Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $server -Continue + } + Write-Message -Level Verbose -Message "Getting publisher for $server" + + try { + $publisher = $replServer.DistributionPublishers + } catch { + Stop-Function -Message "Unable to get publisher for" -ErrorRecord $_ -Target $server -Continue + } + + # fails if there isn't any + if ($publisher) { + $publisher | Add-Member -Type NoteProperty -Name ComputerName -Value $server.ComputerName -Force + $publisher | Add-Member -Type NoteProperty -Name InstanceName -Value $server.ServiceName -Force + $publisher | Add-Member -Type NoteProperty -Name SqlInstance -Value $server.DomainInstanceName -Force + } + + Select-DefaultView -InputObject $publisher -Property ComputerName, InstanceName, SqlInstance, Status, WorkingDirectory, DistributionDatabase, DistributionPublications, PublisherType, Name + + } + } +} \ No newline at end of file diff --git a/public/Get-DbaRepServer.ps1 b/public/Get-DbaReplServer.ps1 similarity index 56% rename from public/Get-DbaRepServer.ps1 rename to public/Get-DbaReplServer.ps1 index 9a9d692110..89c6ef0a6d 100644 --- a/public/Get-DbaRepServer.ps1 +++ b/public/Get-DbaReplServer.ps1 @@ -1,13 +1,13 @@ -function Get-DbaRepServer { +function Get-DbaReplServer { <# .SYNOPSIS Gets a replication server object .DESCRIPTION - Gets a replication server object + Gets a replication server object. - All replication commands need SQL Server Management Studio installed and are therefore currently not supported. - Have a look at this issue to get more information: https://github.com/dataplat/dbatools/issues/7428 + Note: The ReplicationDatabases property gets the databases enabled for replication in the connected instance of Microsoft SQL Server/. + Not necessarily the databases that are actually replicated. .PARAMETER SqlInstance The target SQL Server instance or instances @@ -33,15 +33,15 @@ function Get-DbaRepServer { License: MIT https://opensource.org/licenses/MIT .LINK - https://dbatools.io/Get-DbaRepServer + https://dbatools.io/Get-DbaReplServer .EXAMPLE - PS C:\> Get-DbaRepServer -SqlInstance sql2016 + PS C:\> Get-DbaReplServer -SqlInstance sql2016 Gets the replication server object for sql2016 using Windows authentication .EXAMPLE - PS C:\> Get-DbaRepServer -SqlInstance sql2016 -SqlCredential repadmin + PS C:\> Get-DbaReplServer -SqlInstance sql2016 -SqlCredential repadmin Gets the replication server object for sql2016 using SQL authentication @@ -60,11 +60,16 @@ function Get-DbaRepServer { if (Test-FunctionInterrupt) { return } foreach ($instance in $SqlInstance) { try { - # use System.Data instead of Microsoft.Data - $sqlconn = New-SqlConnection -SqlInstance $instance -SqlCredential $SqlCredential - New-Object Microsoft.SqlServer.Replication.ReplicationServer $sqlconn + $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential + $replServer = New-Object Microsoft.SqlServer.Replication.ReplicationServer + $replServer.ConnectionContext = $Server.ConnectionContext.SqlConnectionObject + $replServer | Add-Member -Type NoteProperty -Name ComputerName -Value $server.ComputerName -Force + $replServer | Add-Member -Type NoteProperty -Name InstanceName -Value $server.ServiceName -Force + $replServer | Add-Member -Type NoteProperty -Name SqlInstance -Value $server.DomainInstanceName -Force + + Select-DefaultView -InputObject $replServer -Property ComputerName, InstanceName, SqlInstance, IsDistributor, IsPublisher, DistributionServer, DistributionDatabase } catch { - Stop-Function -Message "Error occurred while establishing connection to $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue + Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue } } } diff --git a/public/Get-DbaReplSubscription.ps1 b/public/Get-DbaReplSubscription.ps1 new file mode 100644 index 0000000000..3169ffe18e --- /dev/null +++ b/public/Get-DbaReplSubscription.ps1 @@ -0,0 +1,149 @@ +function Get-DbaReplSubscription { + <# + .SYNOPSIS + Displays all subscriptions for a publication. + + .DESCRIPTION + Displays all subscriptions for a publication + + .PARAMETER SqlInstance + The target SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER Database + The database(s) to process. If unspecified, all databases will be processed. + + .PARAMETER PublicationName + The name of the publication. + + .PARAMETER SubscriberName + The subscriber SQL Server instance name. + + .PARAMETER SubscriptionDatabase + The name of the subscription database. + + .PARAMETER Type + Limit by specific type of publication. Valid choices include: Transactional, Merge, Snapshot + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .NOTES + Tags: repl, Replication + Author: Jess Pomfret (@jpomfret), jesspomfret.com + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/Get-DbaReplSubscription + + .EXAMPLE + PS C:\> Get-DbaReplSubscription -SqlInstance mssql1 + + Return all subscriptions for all publications on server mssql1. + + .EXAMPLE + PS C:\> Get-DbaReplSubscription -SqlInstance mssql1 -Database TestDB + + Return all subscriptions for all publications on server mssql1 for only the TestDB database. + + .EXAMPLE + PS C:\> Get-DbaReplSubscription -SqlInstance mssql1 -PublicationName Mergey + + Return all subscriptions for the publication Mergey on server mssql1. + + .EXAMPLE + PS C:\> Get-DbaReplSubscription -SqlInstance mssql1 -Type Push + + Return all subscriptions for all transactional publications on server mssql1. + + .EXAMPLE + PS C:\> Get-DbaReplSubscription -SqlInstance mssql1 -SubscriberName mssql2 + + Return all subscriptions for all publications on server mssql1 where the subscriber is mssql2. + + .EXAMPLE + PS C:\> Get-DbaReplSubscription -SqlInstance mssql1 -SubscriptionDatabase TestDB + + Return all subscriptions for all publications on server mssql1 where the subscription database is TestDB. + + #> + [CmdletBinding()] + param ( + [Parameter(Mandatory, ValueFromPipeline)] + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [Object[]]$Database, + [String[]]$PublicationName, + [DbaInstanceParameter[]]$SubscriberName, + [Object[]]$SubscriptionDatabase, + [Alias("PublicationType")] + [ValidateSet("Push", "Pull")] + [Object[]]$Type, + [Switch]$EnableException + ) + process { + if (Test-FunctionInterrupt) { return } + + foreach ($instance in $SqlInstance) { + try { + $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential + } catch { + Stop-Function -Message "Error occurred while establishing connection to $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue + } + + try { + $publications = Get-DbaReplPublication -SqlInstance $server -EnableException:$EnableException + + if ($Database) { + $publications = $publications | Where-Object DatabaseName -in $Database + } + + if ($PublicationName) { + $publications = $publications | Where-Object Name -in $PublicationName + } + + } catch { + Stop-Function -Message "Error occurred while getting publications from $instance" -ErrorRecord $_ -Target $instance -Continue + } + + try { + foreach ($subs in $publications.Subscriptions) { + Write-Message -Level Verbose -Message ('Get subscriptions for {0}' -f $sub.PublicationName) + + if ($SubscriberName) { + $subs = $subs | Where-Object SubscriberName -eq $SubscriberName + } + + if ($SubscriptionDatabase) { + $subs = $subs | Where-Object SubscriptionDBName -eq $SubscriptionDatabase + } + + if ($Type) { + $subs = $subs | Where-Object SubscriptionType -eq $Type + } + + foreach ($sub in $subs) { + Add-Member -Force -InputObject $sub -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName + Add-Member -Force -InputObject $sub -MemberType NoteProperty -Name InstanceName -Value $server.ServiceName + Add-Member -Force -InputObject $sub -MemberType NoteProperty -Name SqlInstance -Value $server.DomainInstanceName + + Select-DefaultView -InputObject $sub -Property ComputerName, InstanceName, SqlInstance, DatabaseName, PublicationName, Name, SubscriberName, SubscriptionDBName, SubscriptionType + } + } + } catch { + Stop-Function -Message "Error occurred while getting subscriptions from $instance" -ErrorRecord $_ -Target $instance -Continue + } + } + } +} \ No newline at end of file diff --git a/public/Get-DbaSpConfigure.ps1 b/public/Get-DbaSpConfigure.ps1 index e6259968c3..d239a52d9f 100644 --- a/public/Get-DbaSpConfigure.ps1 +++ b/public/Get-DbaSpConfigure.ps1 @@ -83,7 +83,7 @@ function Get-DbaSpConfigure { [switch]$EnableException ) begin { - $smoName = [pscustomobject]@{ + $smoName = [PSCustomObject]@{ "access check cache bucket count" = "AccessCheckCacheBucketCount" "access check cache quota" = "AccessCheckCacheQuota" "Ad Hoc Distributed Queries" = "AdHocDistributedQueriesEnabled" @@ -224,7 +224,7 @@ function Get-DbaSpConfigure { if (!([string]::IsNullOrEmpty($prop.RunValue))) { $DisplayName = $prop.DisplayName - [pscustomobject]@{ + [PSCustomObject]@{ ServerName = $server.Name ComputerName = $server.ComputerName InstanceName = $server.ServiceName diff --git a/public/Get-DbaSpinLockStatistic.ps1 b/public/Get-DbaSpinLockStatistic.ps1 index 13db299155..4469ed82c8 100644 --- a/public/Get-DbaSpinLockStatistic.ps1 +++ b/public/Get-DbaSpinLockStatistic.ps1 @@ -74,12 +74,12 @@ function Get-DbaSpinLockStatistic { BEGIN { $sql = "SELECT - name, - collisions, - spins, - spins_per_collision, - sleep_time, - backoffs + name, + collisions, + spins, + spins_per_collision, + sleep_time, + backoffs FROM sys.dm_os_spinlock_stats;" Write-Message -Level Debug -Message $sql diff --git a/public/Get-DbaSpn.ps1 b/public/Get-DbaSpn.ps1 index 599c304c70..3819510212 100644 --- a/public/Get-DbaSpn.ps1 +++ b/public/Get-DbaSpn.ps1 @@ -97,7 +97,7 @@ function Get-DbaSpn { # $serviceclass = ($spn -Split "\/")[0] # } } - [pscustomobject] @{ + [PSCustomObject] @{ Input = $Account AccountName = $Account ServiceClass = "MSSQLSvc" # $serviceclass @@ -134,7 +134,7 @@ function Get-DbaSpn { if ($accountName) { if ($accountName -eq $spn.InstanceServiceAccount) { - [pscustomobject] @{ + [PSCustomObject] @{ Input = $computer AccountName = $spn.InstanceServiceAccount ServiceClass = "MSSQLSvc" @@ -143,7 +143,7 @@ function Get-DbaSpn { } } } else { - [pscustomobject] @{ + [PSCustomObject] @{ Input = $computer AccountName = $spn.InstanceServiceAccount ServiceClass = "MSSQLSvc" diff --git a/public/Get-DbaStartupParameter.ps1 b/public/Get-DbaStartupParameter.ps1 index 7e4dbc6104..9763e7a300 100644 --- a/public/Get-DbaStartupParameter.ps1 +++ b/public/Get-DbaStartupParameter.ps1 @@ -187,4 +187,4 @@ function Get-DbaStartupParameter { } } } -} +} \ No newline at end of file diff --git a/public/Get-DbaTcpPort.ps1 b/public/Get-DbaTcpPort.ps1 index afe335e204..7dc3517320 100644 --- a/public/Get-DbaTcpPort.ps1 +++ b/public/Get-DbaTcpPort.ps1 @@ -128,7 +128,7 @@ function Get-DbaTcpPort { $sql = "SELECT local_net_address,local_tcp_port FROM sys.dm_exec_connections WHERE session_id = @@SPID" $port = $server.Query($sql) - [PsCustomObject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaTraceFlag.ps1 b/public/Get-DbaTraceFlag.ps1 index 94a179fead..611eeaec3e 100644 --- a/public/Get-DbaTraceFlag.ps1 +++ b/public/Get-DbaTraceFlag.ps1 @@ -83,7 +83,7 @@ function Get-DbaTraceFlag { } foreach ($tflag in $tflags) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Get-DbaWaitResource.ps1 b/public/Get-DbaWaitResource.ps1 index 124846ba9b..b5deea40e3 100644 --- a/public/Get-DbaWaitResource.ps1 +++ b/public/Get-DbaWaitResource.ps1 @@ -59,7 +59,7 @@ function Get-DbaWaitResource { param ( [parameter(Mandatory)] [DbaInstance]$SqlInstance, - [PsCredential]$SqlCredential, + [PSCredential]$SqlCredential, [parameter(Mandatory, ValueFromPipeline)] [string]$WaitResource, [switch]$Row, @@ -110,7 +110,7 @@ function Get-DbaWaitResource { if ($null -eq $object) { Write-Message -Warning "Object could not be found. Could have been removed, or could be a transcription error copying the Wait_resource to sowerShell" } - [PsCustomObject]@{ + [PSCustomObject]@{ DatabaseID = $dbId DatabaseName = $dbName DataFileName = $dataFile.name @@ -139,7 +139,7 @@ function Get-DbaWaitResource { Write-Message -Level Warning -Message "Heap or B-Tree with ID $($matches.frodo) can not be found in $dbName on $server" return } - $output = [PsCustomObject]@{ + $output = [PSCustomObject]@{ DatabaseID = $dbId DatabaseName = $dbName SchemaName = $index.SchemaName diff --git a/public/Get-DbaWaitStatistic.ps1 b/public/Get-DbaWaitStatistic.ps1 index 4806f2eedd..bdb1937941 100644 --- a/public/Get-DbaWaitStatistic.ps1 +++ b/public/Get-DbaWaitStatistic.ps1 @@ -92,7 +92,7 @@ function Get-DbaWaitStatistic { begin { - $details = [pscustomobject]@{ + $details = [PSCustomObject]@{ CXPACKET = "This indicates parallelism, not necessarily that there's a problem. The coordinator thread in a parallel query always accumulates these waits. If the parallel threads are not given equal amounts of work to do, or one thread blocks, the waiting threads will also accumulate CXPACKET waits, which will make them aggregate a lot faster - this is a problem. One thread may have a lot more to do than the others, and so the whole query is blocked while the long-running thread completes. If this is combined with a high number of PAGEIOLATCH_XX waits, it could be large parallel table scans going on because of incorrect non-clustered indexes, or a bad query plan. If neither of these are the issue, you might want to try setting MAXDOP to 4, 2, or 1 for the offending queries (or possibly the whole instance). Make sure that if you have a NUMA system that you try setting MAXDOP to the number of cores in a single NUMA node first to see if that helps the problem. You also need to consider the MAXDOP effect on a mixed-load system. Play with the cost threshold for parallelism setting (bump it up to, say, 25) before reducing the MAXDOP of the whole instance. And don't forget Resource Governor in Enterprise Edition of SQL Server 2008 onward that allows DOP governing for a particular group of connections to the server." PAGEIOLATCH_XX = "This is where SQL Server is waiting for a data page to be read from disk into memory. It may indicate a bottleneck at the IO subsystem level (which is a common knee-jerk response to seeing these), but why is the I/O subsystem having to service so many reads? It could be buffer pool/memory pressure (i.e. not enough memory for the workload), a sudden change in query plans causing a large parallel scan instead of a seek, plan cache bloat, or a number of other things. Don't assume the root cause is the I/O subsystem." ASYNC_NETWORK_IO = "This is usually where SQL Server is waiting for a client to finish consuming data. It could be that the client has asked for a very large amount of data or just that it's consuming it reeeeeally slowly because of poor programming - I rarely see this being a network issue. Clients often process one row at a time - called RBAR or Row-By-Agonizing-Row - instead of caching the data on the client and acknowledging to SQL Server immediately." @@ -133,7 +133,7 @@ function Get-DbaWaitStatistic { # Thanks Brent Ozar via https://gist.github.com/BrentOzar/42e82ee0603a1917c17d74c3fca26d34 # Thanks Marcin Gminski via https://www.dropbox.com/s/x3zr7u18tc1ojey/WaitStats.sql?dl=0 - $category = [pscustomobject]@{ + $category = [PSCustomObject]@{ ASYNC_IO_COMPLETION = 'Other Disk IO' ASYNC_NETWORK_IO = 'Network IO' BACKUPIO = 'Other Disk IO' diff --git a/public/Get-DbaWsfcDisk.ps1 b/public/Get-DbaWsfcDisk.ps1 index 65e653a9c4..b3e1b5e0f2 100644 --- a/public/Get-DbaWsfcDisk.ps1 +++ b/public/Get-DbaWsfcDisk.ps1 @@ -49,7 +49,7 @@ function Get-DbaWsfcDisk { $disks = $resource | Get-CimAssociatedInstance -ResultClassName MSCluster_Disk foreach ($disk in $disks) { $diskpart = $disk | Get-CimAssociatedInstance -ResultClassName MSCluster_DiskPartition - [pscustomobject]@{ + [PSCustomObject]@{ ClusterName = $resource.ClusterName ClusterFqdn = $resource.ClusterFqdn ResourceGroup = $resource.OwnerGroup diff --git a/public/Get-DbaXESessionTemplate.ps1 b/public/Get-DbaXESessionTemplate.ps1 index 4111de9c4a..8b368c41a8 100644 --- a/public/Get-DbaXESessionTemplate.ps1 +++ b/public/Get-DbaXESessionTemplate.ps1 @@ -109,7 +109,7 @@ function Get-DbaXESessionTemplate { ($session.event_session.TemplateName.'#text' -match $Pattern) -or ($meta.Source -match $Pattern) ) { - [pscustomobject]@{ + [PSCustomObject]@{ Name = $session.event_session.name Category = $session.event_session.TemplateCategory.'#text' Source = $meta.Source @@ -121,7 +121,7 @@ function Get-DbaXESessionTemplate { } | Select-DefaultView -ExcludeProperty File, TemplateName, Path } } else { - [pscustomobject]@{ + [PSCustomObject]@{ Name = $session.event_session.name Category = $session.event_session.TemplateCategory.'#text' Source = $meta.Source diff --git a/public/Grant-DbaAgPermission.ps1 b/public/Grant-DbaAgPermission.ps1 index 0fa613b014..ab53904f38 100644 --- a/public/Grant-DbaAgPermission.ps1 +++ b/public/Grant-DbaAgPermission.ps1 @@ -170,7 +170,7 @@ function Grant-DbaAgPermission { try { $bigperms = New-Object Microsoft.SqlServer.Management.Smo.ObjectPermissionSet([Microsoft.SqlServer.Management.Smo.ObjectPermission]::$perm) $endpoint.Grant($bigperms, $account.Name) - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $account.ComputerName InstanceName = $account.InstanceName SqlInstance = $account.SqlInstance @@ -197,7 +197,7 @@ function Grant-DbaAgPermission { try { $bigperms = New-Object Microsoft.SqlServer.Management.Smo.ObjectPermissionSet([Microsoft.SqlServer.Management.Smo.ObjectPermission]::$perm) $ag.Grant($bigperms, $account.Name) - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $account.ComputerName InstanceName = $account.InstanceName SqlInstance = $account.SqlInstance @@ -215,4 +215,4 @@ function Grant-DbaAgPermission { } } } -} +} \ No newline at end of file diff --git a/public/Import-DbaCsv.ps1 b/public/Import-DbaCsv.ps1 index 2f8209a557..b7e622c5b9 100644 --- a/public/Import-DbaCsv.ps1 +++ b/public/Import-DbaCsv.ps1 @@ -259,7 +259,7 @@ function Import-DbaCsv { [object[]]$Path, [Parameter(Mandatory)] [DbaInstanceParameter[]]$SqlInstance, - [pscredential]$SqlCredential, + [PSCredential]$SqlCredential, [Parameter(Mandatory)] [string]$Database, [string]$Table, @@ -728,7 +728,7 @@ function Import-DbaCsv { Write-Message -Level Verbose -Message "$($script:totalRowsCopied) total rows copied" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Install-DbaInstance.ps1 b/public/Install-DbaInstance.ps1 index 17b388c394..04c4a70223 100644 --- a/public/Install-DbaInstance.ps1 +++ b/public/Install-DbaInstance.ps1 @@ -296,13 +296,13 @@ function Install-DbaInstance { [string]$ProductID, [string]$AsCollation, [string]$SqlCollation, - [pscredential]$EngineCredential, - [pscredential]$AgentCredential, - [pscredential]$ASCredential, - [pscredential]$ISCredential, - [pscredential]$RSCredential, - [pscredential]$FTCredential, - [pscredential]$PBEngineCredential, + [PSCredential]$EngineCredential, + [PSCredential]$AgentCredential, + [PSCredential]$ASCredential, + [PSCredential]$ISCredential, + [PSCredential]$RSCredential, + [PSCredential]$FTCredential, + [PSCredential]$PBEngineCredential, [string]$SaveConfiguration, [switch]$PerformVolumeMaintenanceTasks, [switch]$Restart, @@ -374,7 +374,7 @@ function Install-DbaInstance { # updates a service account entry and returns the password as a command line argument Param ( $Node, - [pscredential]$Credential, + [PSCredential]$Credential, [string]$AccountName, [string]$PasswordName = $AccountName.Replace('SVCACCOUNT', 'SVCPASSWORD') ) @@ -814,4 +814,4 @@ function Install-DbaInstance { $actionPlan | Invoke-Parallel -ImportModules -ImportVariables @invokeParallelSplat } } -} +} \ No newline at end of file diff --git a/public/Install-DbaMaintenanceSolution.ps1 b/public/Install-DbaMaintenanceSolution.ps1 index bff240616b..efd9dafe5b 100644 --- a/public/Install-DbaMaintenanceSolution.ps1 +++ b/public/Install-DbaMaintenanceSolution.ps1 @@ -632,7 +632,7 @@ function Install-DbaMaintenanceSolution { if ($query) { # then whatif wasn't passed - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Install-DbaMultiTool.ps1 b/public/Install-DbaMultiTool.ps1 index b73a8abb7d..4de302b325 100644 --- a/public/Install-DbaMultiTool.ps1 +++ b/public/Install-DbaMultiTool.ps1 @@ -176,4 +176,4 @@ function Install-DbaMultiTool { Write-Message -Level Verbose -Message "Finished installing/updating DbaMultiTool stored procedures in $Database on $instance." } } -} +} \ No newline at end of file diff --git a/public/Install-DbaWhoIsActive.ps1 b/public/Install-DbaWhoIsActive.ps1 index 2d031318f6..dfe14893c6 100644 --- a/public/Install-DbaWhoIsActive.ps1 +++ b/public/Install-DbaWhoIsActive.ps1 @@ -87,7 +87,7 @@ function Install-DbaWhoIsActive { param ( [parameter(Mandatory, ValueFromPipeline, Position = 0)] [DbaInstanceParameter[]]$SqlInstance, - [PsCredential]$SqlCredential, + [PSCredential]$SqlCredential, [ValidateScript( { Test-Path -Path $_ -PathType Leaf })] [string]$LocalFile, [object]$Database, @@ -200,4 +200,4 @@ function Install-DbaWhoIsActive { } } } -} +} \ No newline at end of file diff --git a/public/Invoke-DbaAdvancedInstall.ps1 b/public/Invoke-DbaAdvancedInstall.ps1 index 294c152d72..c5e9f1cb80 100644 --- a/public/Invoke-DbaAdvancedInstall.ps1 +++ b/public/Invoke-DbaAdvancedInstall.ps1 @@ -105,8 +105,8 @@ function Invoke-DbaAdvancedInstall { [string]$SaveConfiguration, [ValidateSet('Default', 'Basic', 'Negotiate', 'NegotiateWithImplicitCredential', 'Credssp', 'Digest', 'Kerberos')] [string]$Authentication = 'Credssp', - [pscredential]$Credential, - [pscredential]$SaCredential, + [PSCredential]$Credential, + [PSCredential]$SaCredential, [switch]$NoPendingRenameCheck, [switch]$EnableException ) @@ -114,7 +114,7 @@ function Invoke-DbaAdvancedInstall { # Reads Summary.txt from the SQL Server Installation Log folder Param ( [DbaInstanceParameter]$ComputerName, - [pscredential]$Credential, + [PSCredential]$Credential, [parameter(Mandatory)] [version]$Version ) @@ -155,7 +155,7 @@ function Invoke-DbaAdvancedInstall { return Invoke-Command2 @params } $isLocalHost = ([DbaInstanceParameter]$ComputerName).IsLocalHost - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $ComputerName Version = $Version SACredential = $SaCredential @@ -342,4 +342,4 @@ function Invoke-DbaAdvancedInstall { } $output | Select-DefaultView -Property ComputerName, InstanceName, Version, Port, Successful, Restarted, Installer, ExitCode, LogFile, Notes Write-Progress -Activity $activity -Completed -} +} \ No newline at end of file diff --git a/public/Invoke-DbaAdvancedRestore.ps1 b/public/Invoke-DbaAdvancedRestore.ps1 index c9b9129532..98bad3d920 100644 --- a/public/Invoke-DbaAdvancedRestore.ps1 +++ b/public/Invoke-DbaAdvancedRestore.ps1 @@ -382,7 +382,7 @@ function Invoke-DbaAdvancedRestore { $RestoreDirectory = ((Split-Path $backup.FileList.PhysicalName -Parent) | Sort-Object -Unique).Replace('\', $pathSep) -Join ',' if ([bool]($backup.psobject.Properties.Name -contains 'CompressedBackupSize')) { - $bytes = [pscustomobject]@{ Bytes = $backup.CompressedBackupSize.Byte } + $bytes = [PSCustomObject]@{ Bytes = $backup.CompressedBackupSize.Byte } $sum = ($bytes | Measure-Object -Property Bytes -Sum).Sum $compressedbackupsize = [dbasize]($sum / $backup.FullName.Count) $compressedbackupsizemb = [Math]::Round($sum / $backup.FullName.Count / 1mb, 2) @@ -392,7 +392,7 @@ function Invoke-DbaAdvancedRestore { } if ([bool]($backup.psobject.Properties.Name -contains 'TotalSize')) { - $bytes = [pscustomobject]@{ Bytes = $backup.TotalSize.Byte } + $bytes = [PSCustomObject]@{ Bytes = $backup.TotalSize.Byte } $sum = ($bytes | Measure-Object -Property Bytes -Sum).Sum $backupsize = [dbasize]($sum / $backup.FullName.Count) $backupsizemb = [Math]::Round($sum / $backup.FullName.Count / 1mb, 2) @@ -451,4 +451,4 @@ function Invoke-DbaAdvancedRestore { Write-Progress -id 1 -Activity "Finished" -Completed } } -} +} \ No newline at end of file diff --git a/public/Invoke-DbaAdvancedUpdate.ps1 b/public/Invoke-DbaAdvancedUpdate.ps1 index 5fe2572a1d..d61b9c6f75 100644 --- a/public/Invoke-DbaAdvancedUpdate.ps1 +++ b/public/Invoke-DbaAdvancedUpdate.ps1 @@ -78,7 +78,7 @@ Function Invoke-DbaAdvancedUpdate { [bool]$Restart, [ValidateSet('Default', 'Basic', 'Negotiate', 'NegotiateWithImplicitCredential', 'Credssp', 'Digest', 'Kerberos')] [string]$Authentication = 'Credssp', - [pscredential]$Credential, + [PSCredential]$Credential, [string]$ExtractPath, [string[]]$ArgumentList, [switch]$NoPendingRenameCheck, diff --git a/public/Invoke-DbaAzSqlDbTip.ps1 b/public/Invoke-DbaAzSqlDbTip.ps1 index ee2f191e7d..eed68b8922 100644 --- a/public/Invoke-DbaAzSqlDbTip.ps1 +++ b/public/Invoke-DbaAzSqlDbTip.ps1 @@ -218,11 +218,11 @@ function Invoke-DbaAzSqlDbTip { InstanceName = $connection.Name SqlInstance = $connection.DomainInstanceName Database = $db - tip_id = $PsItem.tip_id - description = $PsItem.description - confidence_percent = $PsItem.confidence_percent - additional_info_url = $PsItem.additional_info_url - details = $PsItem.details + tip_id = $PSItem.tip_id + description = $PSItem.description + confidence_percent = $PSItem.confidence_percent + additional_info_url = $PSItem.additional_info_url + details = $PSItem.details } } } catch { diff --git a/public/Invoke-DbaBalanceDataFiles.ps1 b/public/Invoke-DbaBalanceDataFiles.ps1 index 237dfbbe44..a0a0c899fd 100644 --- a/public/Invoke-DbaBalanceDataFiles.ps1 +++ b/public/Invoke-DbaBalanceDataFiles.ps1 @@ -352,7 +352,7 @@ function Invoke-DbaBalanceDataFiles { Write-Message -Message "Retrieving data files after data move" -Level Verbose $dataFilesEnding = Get-DbaDbFile -SqlInstance $server -Database $db.Name | Where-Object { $_.TypeDescription -eq 'ROWS' } | Select-Object ID, LogicalName, PhysicalName, Size, UsedSpace, AvailableSpace | Sort-Object ID - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Invoke-DbaCycleErrorLog.ps1 b/public/Invoke-DbaCycleErrorLog.ps1 index b77d46d613..e53f602a5a 100644 --- a/public/Invoke-DbaCycleErrorLog.ps1 +++ b/public/Invoke-DbaCycleErrorLog.ps1 @@ -108,7 +108,7 @@ function Invoke-DbaCycleErrorLog { $logs = $logToCycle -join ',' if ($Pscmdlet.ShouldProcess($server, "Cycle the log(s): $logs")) { $null = $server.Query($sql) - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -118,7 +118,7 @@ function Invoke-DbaCycleErrorLog { } } } catch { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Invoke-DbaDbDataGenerator.ps1 b/public/Invoke-DbaDbDataGenerator.ps1 index ea19c54e6f..99b07e451e 100644 --- a/public/Invoke-DbaDbDataGenerator.ps1 +++ b/public/Invoke-DbaDbDataGenerator.ps1 @@ -399,9 +399,24 @@ function Invoke-DbaDbDataGenerator { $columnobject.MaxValue = $MaxValue } if ($columnobject.ColumnType -in $supportedDataTypes -and $columnobject.MaskingType -eq 'Random' -and $columnobject.SubType -in 'Bool', 'Number', 'Float', 'Byte', 'String') { - $columnValue = Get-DbaRandomizedValue -DataType $columnobject.ColumnType -CharacterString $charstring -Locale $Locale -Min $columnobject.MinValue -Max $columnobject.MaxValue + $randomParams = @{ + DataType = $columnobject.ColumnType + CharacterString = $charstring + Locale = $Locale + Min = $columnobject.MinValue + Max = $columnobject.MaxValue + } + $columnValue = Get-DbaRandomizedValue @randomParams } else { - $columnValue = Get-DbaRandomizedValue -RandomizerType $columnobject.MaskingType -RandomizerSubtype $columnobject.SubType -CharacterString $charstring -Locale $Locale -Min $columnobject.MinValue -Max $columnobject.MaxValue + $randomParams = @{ + RandomizerType = $columnobject.MaskingType + RandomizerSubtype = $columnobject.SubType + CharacterString = $charstring + Locale = $Locale + Min = $columnobject.MinValue + Max = $columnobject.MaxValue + } + $columnValue = Get-DbaRandomizedValue @randomParams } } catch { @@ -456,7 +471,7 @@ function Invoke-DbaDbDataGenerator { try { $null = $transaction.Commit() - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $db.Parent.ComputerName InstanceName = $db.Parent.ServiceName SqlInstance = $db.Parent.DomainInstanceName diff --git a/public/Invoke-DbaDbDataMasking.ps1 b/public/Invoke-DbaDbDataMasking.ps1 index 9735dabcbd..65fd575097 100644 --- a/public/Invoke-DbaDbDataMasking.ps1 +++ b/public/Invoke-DbaDbDataMasking.ps1 @@ -1274,7 +1274,7 @@ function Invoke-DbaDbDataMasking { $maskingStatus = "Successful" } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $db.Parent.ComputerName InstanceName = $db.Parent.ServiceName SqlInstance = $db.Parent.DomainInstanceName diff --git a/public/Invoke-DbaDbLogShipping.ps1 b/public/Invoke-DbaDbLogShipping.ps1 index 84121282f7..ecc4ef64c0 100644 --- a/public/Invoke-DbaDbLogShipping.ps1 +++ b/public/Invoke-DbaDbLogShipping.ps1 @@ -1673,4 +1673,4 @@ function Invoke-DbaDbLogShipping { end { Write-Message -Message "Finished setting up log shipping." -Level Verbose } -} +} \ No newline at end of file diff --git a/public/Invoke-DbaDbMirroring.ps1 b/public/Invoke-DbaDbMirroring.ps1 index 06cd37d95f..0d5c07651c 100644 --- a/public/Invoke-DbaDbMirroring.ps1 +++ b/public/Invoke-DbaDbMirroring.ps1 @@ -383,7 +383,7 @@ function Invoke-DbaDbMirroring { if ($Pscmdlet.ShouldProcess("console", "Showing results")) { - $results = [pscustomobject]@{ + $results = [PSCustomObject]@{ Primary = $Primary Mirror = $currentmirror Witness = $Witness diff --git a/public/Invoke-DbaDbPiiScan.ps1 b/public/Invoke-DbaDbPiiScan.ps1 index a014222991..d539798f82 100644 --- a/public/Invoke-DbaDbPiiScan.ps1 +++ b/public/Invoke-DbaDbPiiScan.ps1 @@ -273,7 +273,7 @@ function Invoke-DbaDbPiiScan { if ($columnobject.DataType.Name -eq "geography") { # Add the results - $piiScanResults += [pscustomobject]@{ + $piiScanResults += [PSCustomObject]@{ ComputerName = $db.Parent.ComputerName InstanceName = $db.Parent.ServiceName SqlInstance = $db.Parent.DomainInstanceName @@ -309,7 +309,7 @@ function Invoke-DbaDbPiiScan { $_.MaskingType -eq $knownName.MaskingType -and $_.MaskingSubType -eq $knownName.MaskingSubType })) { - $piiScanResults += [pscustomobject]@{ + $piiScanResults += [PSCustomObject]@{ ComputerName = $db.Parent.ComputerName InstanceName = $db.Parent.ServiceName SqlInstance = $db.Parent.DomainInstanceName @@ -379,7 +379,7 @@ function Invoke-DbaDbPiiScan { $_.Country -eq $patternobject.Country -and $_.CountryCode -eq $patternobject.CountryCode })) { - $piiScanResults += [pscustomobject]@{ + $piiScanResults += [PSCustomObject]@{ ComputerName = $db.Parent.ComputerName InstanceName = $db.Parent.ServiceName SqlInstance = $db.Parent.DomainInstanceName diff --git a/public/Invoke-DbaDbTransfer.ps1 b/public/Invoke-DbaDbTransfer.ps1 index 034582de86..0261826186 100644 --- a/public/Invoke-DbaDbTransfer.ps1 +++ b/public/Invoke-DbaDbTransfer.ps1 @@ -199,7 +199,7 @@ function Invoke-DbaDbTransfer { return } - return [pscustomobject]@{ + return [PSCustomObject]@{ SourceInstance = $transfer.Database.Parent.Name SourceDatabase = $transfer.Database.Name DestinationInstance = $transfer.DestinationServer diff --git a/public/Invoke-DbaDiagnosticQuery.ps1 b/public/Invoke-DbaDiagnosticQuery.ps1 index dfcb14e789..968a366c73 100644 --- a/public/Invoke-DbaDiagnosticQuery.ps1 +++ b/public/Invoke-DbaDiagnosticQuery.ps1 @@ -131,7 +131,7 @@ function Invoke-DbaDiagnosticQuery { Run diagnostic queries targeted at specific database, and only run database level queries against this database. #> [CmdletBinding(SupportsShouldProcess)] - [OutputType([pscustomobject[]])] + [OutputType([PSCustomObject[]])] param ( [parameter(Mandatory, ValueFromPipeline, Position = 0)] [DbaInstanceParameter[]]$SqlInstance, @@ -201,7 +201,7 @@ function Invoke-DbaDiagnosticQuery { if ($file.BaseName.Split("_")[2] -eq $currentdate) { $parsedscript = Invoke-DbaDiagnosticQueryScriptParser -filename $file.fullname -ExcludeQueryTextColumn:$ExcludeQueryTextColumn -ExcludePlanColumn:$ExcludePlanColumn -NoColumnParsing:$NoColumnParsing - $newscript = [pscustomobject]@{ + $newscript = [PSCustomObject]@{ Version = $file.Basename.Split("_")[1] Script = $parsedscript } @@ -323,7 +323,7 @@ function Invoke-DbaDiagnosticQuery { $result = $server.Query($scriptpart.Text) Write-Message -Level Verbose -Message "Processed $($scriptpart.QueryName) on $instance" if (-not $result) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -341,7 +341,7 @@ function Invoke-DbaDiagnosticQuery { Write-Message -Level Verbose -Message ('Some error has occurred on Server: {0} - Script: {1}, result unavailable' -f $instance, $scriptpart.QueryName) -Target $instance -ErrorRecord $_ } if ($result) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -360,7 +360,7 @@ function Invoke-DbaDiagnosticQuery { } else { # if running WhatIf, then return the queries that would be run as an object, not just whatif output - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -398,7 +398,7 @@ function Invoke-DbaDiagnosticQuery { try { $result = $server.Query($scriptpart.Text, $currentDb) if (-not $result) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -417,7 +417,7 @@ function Invoke-DbaDiagnosticQuery { } if ($result) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -435,7 +435,7 @@ function Invoke-DbaDiagnosticQuery { } else { # if running WhatIf, then return the queries that would be run as an object, not just whatif output - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Invoke-DbaPfRelog.ps1 b/public/Invoke-DbaPfRelog.ps1 index 5619a2a834..1903d779dd 100644 --- a/public/Invoke-DbaPfRelog.ps1 +++ b/public/Invoke-DbaPfRelog.ps1 @@ -245,7 +245,7 @@ function Invoke-DbaPfRelog { if ($args) { $file = $args } else { - $file = $psitem + $file = $PSItem } $item = Get-ChildItem -Path $file -ErrorAction SilentlyContinue diff --git a/public/Invoke-DbaQuery.ps1 b/public/Invoke-DbaQuery.ps1 index 9140d1fade..34c70a1ae8 100644 --- a/public/Invoke-DbaQuery.ps1 +++ b/public/Invoke-DbaQuery.ps1 @@ -125,11 +125,11 @@ function Invoke-DbaQuery { .EXAMPLE PS C:\> $inparam = @() - PS C:\> $inparam += [pscustomobject]@{ + PS C:\> $inparam += [PSCustomObject]@{ >> somestring = 'string1' >> somedate = '2021-07-15T01:02:00' >> } - PS C:\> $inparam += [pscustomobject]@{ + PS C:\> $inparam += [PSCustomObject]@{ >> somestring = 'string2' >> somedate = '2021-07-15T02:03:00' >> } @@ -160,7 +160,7 @@ function Invoke-DbaQuery { [Parameter(ParameterSetName = 'File', Position = 0)] [Parameter(ParameterSetName = 'SMO', Position = 0)] [DbaInstance[]]$SqlInstance, - [PsCredential]$SqlCredential, + [PSCredential]$SqlCredential, [string]$Database, [Parameter(Mandatory, ParameterSetName = "Query")] [string]$Query, diff --git a/public/Invoke-DbaXEReplay.ps1 b/public/Invoke-DbaXEReplay.ps1 index 64b583dff1..b6f7fb8d69 100644 --- a/public/Invoke-DbaXEReplay.ps1 +++ b/public/Invoke-DbaXEReplay.ps1 @@ -70,7 +70,7 @@ function Invoke-DbaXEReplay { param ( [Parameter(Mandatory)] [DbaInstance[]]$SqlInstance, - [PsCredential]$SqlCredential, + [PSCredential]$SqlCredential, [string[]]$Database, [string[]]$Event = @('sql_batch_completed', 'rcp_completed'), [Parameter(Mandatory, ValueFromPipeline)] diff --git a/public/Invoke-DbatoolsFormatter.ps1 b/public/Invoke-DbatoolsFormatter.ps1 index d1b0d0bdb2..ff313b90b6 100644 --- a/public/Invoke-DbatoolsFormatter.ps1 +++ b/public/Invoke-DbatoolsFormatter.ps1 @@ -104,9 +104,18 @@ function Invoke-DbatoolsFormatter { } } $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False + $correctCase = @( + 'DbaInstanceParameter' + 'PSCredential' + 'PSCustomObject' + 'PSItem' + ) $realContent = @() - #trim whitespace lines foreach ($line in $content.Split("`n")) { + foreach ($item in $correctCase) { + $line = $line -replace $item, $item + } + #trim whitespace lines $realContent += $line.Replace("`t", " ").TrimEnd() } [System.IO.File]::WriteAllText($realPath, ($realContent -Join "$OSEOL"), $Utf8NoBomEncoding) diff --git a/public/Invoke-DbatoolsRenameHelper.ps1 b/public/Invoke-DbatoolsRenameHelper.ps1 index 5203db1bff..5e2f6ec31e 100644 --- a/public/Invoke-DbatoolsRenameHelper.ps1 +++ b/public/Invoke-DbatoolsRenameHelper.ps1 @@ -313,7 +313,7 @@ function Invoke-DbatoolsRenameHelper { if ($Pscmdlet.ShouldProcess($file, "Replacing $($name.Key) with $($name.Value)")) { $content = (Get-Content -Path $file -Raw).Replace($name.Key, $name.Value).Trim() Set-Content -Path $file -Encoding $Encoding -Value $content - [pscustomobject]@{ + [PSCustomObject]@{ Path = $file Pattern = $name.Key ReplacedWith = $name.Value @@ -327,7 +327,7 @@ function Invoke-DbatoolsRenameHelper { if ($Pscmdlet.ShouldProcess($file, "Replacing $($name.Key) with $($name.Value)")) { $content = ((Get-Content -Path $file -Raw) -Replace "\b$($name.Key)\b", $name.Value).Trim() Set-Content -Path $file -Encoding $Encoding -Value $content - [pscustomobject]@{ + [PSCustomObject]@{ Path = $file Pattern = $name.Key ReplacedWith = $name.Value @@ -337,4 +337,4 @@ function Invoke-DbatoolsRenameHelper { } } } -} +} \ No newline at end of file diff --git a/public/Mount-DbaDatabase.ps1 b/public/Mount-DbaDatabase.ps1 index 472deebc4b..45670fbceb 100644 --- a/public/Mount-DbaDatabase.ps1 +++ b/public/Mount-DbaDatabase.ps1 @@ -133,7 +133,7 @@ function Mount-DbaDatabase { try { $server.AttachDatabase($db, $FileStructure, $DatabaseOwner, [Microsoft.SqlServer.Management.Smo.AttachOptions]::$AttachOption) - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/New-DbaAgentJob.ps1 b/public/New-DbaAgentJob.ps1 index 5580e695b8..c5a6480fc4 100644 --- a/public/New-DbaAgentJob.ps1 +++ b/public/New-DbaAgentJob.ps1 @@ -421,4 +421,4 @@ function New-DbaAgentJob { Write-Message -Message "Finished creating job(s)." -Level Verbose } -} +} \ No newline at end of file diff --git a/public/New-DbaAgentOperator.ps1 b/public/New-DbaAgentOperator.ps1 index 957fb68f36..87585a7724 100644 --- a/public/New-DbaAgentOperator.ps1 +++ b/public/New-DbaAgentOperator.ps1 @@ -364,4 +364,4 @@ function New-DbaAgentOperator { } } } -} +} \ No newline at end of file diff --git a/public/New-DbaAgentSchedule.ps1 b/public/New-DbaAgentSchedule.ps1 index f2cae0ab81..0fb7be48c7 100644 --- a/public/New-DbaAgentSchedule.ps1 +++ b/public/New-DbaAgentSchedule.ps1 @@ -63,6 +63,8 @@ function New-DbaAgentSchedule { .PARAMETER FrequencySubdayInterval The number of subday type periods to occur between each execution of a job. + The interval needs to be at least 10 seconds long. + .PARAMETER FrequencyRelativeInterval A job's occurrence of FrequencyInterval in each month, if FrequencyInterval is 32 (monthlyrelative). @@ -244,8 +246,11 @@ function New-DbaAgentSchedule { } # Check the subday interval - if (($FrequencySubdayType -in 2, "Seconds", 4, "Minutes") -and (-not ($FrequencySubdayInterval -ge 1 -or $FrequencySubdayInterval -le 59))) { - Stop-Function -Message "Subday interval $FrequencySubdayInterval must be between 1 and 59 when subday type is 'Seconds' or 'Minutes'" -Target $SqlInstance + if (($FrequencySubdayType -in 2, "Seconds") -and (-not ($FrequencySubdayInterval -ge 10 -or $FrequencySubdayInterval -le 59))) { + Stop-Function -Message "Subday interval $FrequencySubdayInterval must be between 10 and 59 when subday type is 'Seconds'" -Target $SqlInstance + return + } elseif (($FrequencySubdayType -in 4, "Minutes") -and (-not ($FrequencySubdayInterval -ge 1 -or $FrequencySubdayInterval -le 59))) { + Stop-Function -Message "Subday interval $FrequencySubdayInterval must be between 1 and 59 when subday type is 'Minutes'" -Target $SqlInstance return } elseif (($FrequencySubdayType -eq 8, "Hours") -and (-not ($FrequencySubdayInterval -ge 1 -and $FrequencySubdayInterval -le 23))) { Stop-Function -Message "Subday interval $FrequencySubdayInterval must be between 1 and 23 when subday type is 'Hours'" -Target $SqlInstance diff --git a/public/New-DbaAvailabilityGroup.ps1 b/public/New-DbaAvailabilityGroup.ps1 index 1fe3cb132a..577626dd97 100644 --- a/public/New-DbaAvailabilityGroup.ps1 +++ b/public/New-DbaAvailabilityGroup.ps1 @@ -668,4 +668,4 @@ function New-DbaAvailabilityGroup { # Get results Get-DbaAvailabilityGroup -SqlInstance $Primary -SqlCredential $PrimarySqlCredential -AvailabilityGroup $Name } -} +} \ No newline at end of file diff --git a/public/New-DbaAzAccessToken.ps1 b/public/New-DbaAzAccessToken.ps1 index a2f831bd56..9a9a1bf1fa 100644 --- a/public/New-DbaAzAccessToken.ps1 +++ b/public/New-DbaAzAccessToken.ps1 @@ -91,7 +91,7 @@ function New-DbaAzAccessToken { [ValidateSet("AzureSqlDb", "ResourceManager", "DataLake", "EventHubs", "KeyVault", "ResourceManager", "ServiceBus", "Storage")] [string]$Subtype = "AzureSqlDb", [object]$Config, - [pscredential]$Credential, + [PSCredential]$Credential, [string]$Tenant = (Get-DbatoolsConfigValue -FullName 'azure.tenantid'), [string]$Thumbprint = (Get-DbatoolsConfigValue -FullName 'azure.certificate.thumbprint'), [ValidateSet('CurrentUser', 'LocalMachine')] diff --git a/public/New-DbaComputerCertificate.ps1 b/public/New-DbaComputerCertificate.ps1 index d4c4eae06f..2df62deff5 100644 --- a/public/New-DbaComputerCertificate.ps1 +++ b/public/New-DbaComputerCertificate.ps1 @@ -241,7 +241,7 @@ function New-DbaComputerCertificate { $allCas = @() foreach ($ca in $cas) { - $allCas += [pscustomobject]@{ + $allCas += [PSCustomObject]@{ CA = $ca | ForEach-Object { $_.Name } Computer = $ca | ForEach-Object { $_.DNSHostName } } @@ -436,4 +436,4 @@ function New-DbaComputerCertificate { } } } -} +} \ No newline at end of file diff --git a/public/New-DbaDacProfile.ps1 b/public/New-DbaDacProfile.ps1 index 6633d27c4e..334b6272d2 100644 --- a/public/New-DbaDacProfile.ps1 +++ b/public/New-DbaDacProfile.ps1 @@ -162,7 +162,7 @@ function New-DbaDacProfile { $publishProfile = Join-Path $Path "$($instanceName.Replace('--','-'))-$db-publish.xml" -ErrorAction Stop Write-Message -Level Verbose -Message "Writing to $publishProfile" $profileTemplate | Out-File $publishProfile -ErrorAction Stop - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.InstanceName SqlInstance = $server.FullName diff --git a/public/New-DbaDbMaskingConfig.ps1 b/public/New-DbaDbMaskingConfig.ps1 index bd4f2982b4..7a53cf5518 100644 --- a/public/New-DbaDbMaskingConfig.ps1 +++ b/public/New-DbaDbMaskingConfig.ps1 @@ -291,7 +291,7 @@ function New-DbaDbMaskingConfig { continue } - $searchObject = [pscustomobject]@{ + $searchObject = [PSCustomObject]@{ ComputerName = $db.Parent.ComputerName InstanceName = $db.Parent.ServiceName SqlInstance = $db.Parent.DomainInstanceName @@ -392,7 +392,7 @@ function New-DbaDbMaskingConfig { if ($columnobject.DataType.Name -eq "geography") { # Add the results - $result = [pscustomobject]@{ + $result = [PSCustomObject]@{ ComputerName = $db.Parent.ComputerName InstanceName = $db.Parent.ServiceName SqlInstance = $db.Parent.DomainInstanceName @@ -413,7 +413,7 @@ function New-DbaDbMaskingConfig { foreach ($pattern in $knownName.Pattern) { if ($null -eq $result -and $columnobject.Name -match $pattern ) { # Add the results - $result = [pscustomobject]@{ + $result = [PSCustomObject]@{ ComputerName = $db.Parent.ComputerName InstanceName = $db.Parent.ServiceName SqlInstance = $db.Parent.DomainInstanceName @@ -460,7 +460,7 @@ function New-DbaDbMaskingConfig { # If there is a result from the match if ($null -eq $result -and $dataset.$($columnobject.Name) -match $patternobject.Pattern) { # Add the results - $result = [pscustomobject]@{ + $result = [PSCustomObject]@{ ComputerName = $db.Parent.ComputerName InstanceName = $db.Parent.ServiceName SqlInstance = $db.Parent.DomainInstanceName diff --git a/public/New-DbaDbTable.ps1 b/public/New-DbaDbTable.ps1 index 768e62b4e0..4f47a15c4a 100644 --- a/public/New-DbaDbTable.ps1 +++ b/public/New-DbaDbTable.ps1 @@ -526,4 +526,4 @@ function New-DbaDbTable { } } } -} +} \ No newline at end of file diff --git a/public/New-DbaDbUser.ps1 b/public/New-DbaDbUser.ps1 index d84f78c46c..082d11ef6c 100644 --- a/public/New-DbaDbUser.ps1 +++ b/public/New-DbaDbUser.ps1 @@ -154,7 +154,8 @@ function New-DbaDbUser { $getDbParam.OnlyAccessible = $True if ($Database) { $getDbParam.Database = $Database - } elseif (-not $IncludeSystem) { + } + if (-not $IncludeSystem) { $getDbParam.ExcludeSystem = $True } if ($ExcludeDatabase) { @@ -169,6 +170,11 @@ function New-DbaDbUser { $databases = Get-DbaDatabase @getDbParam $getValidSchema = Get-DbaDbSchema -InputObject $databases -Schema $DefaultSchema -IncludeSystemSchemas + #This block is required so that correct error message can be returned to the user when incorrect database name is given or the database doesn't exists in the server. + if (-not $Database) { + $Database = $databases.Name + } + foreach ($db in $Database) { $dbSmo = $databases | Where-Object Name -eq $db @@ -180,6 +186,7 @@ function New-DbaDbUser { $userParam = $connParam.Clone() $userParam.Database = $dbSmo.name $userParam.User = $Username + $userParam.EnableException = $True #check if the schema exists if ($dbSmo.Name -in ($getValidSchema).Parent.Name) { @@ -201,7 +208,7 @@ function New-DbaDbUser { } elseif ($userExists -and $Force) { try { Write-Message -Level Verbose -Message "FORCE is used, user [$Username] will be dropped in the database $dbSmo on [$instance]" - Remove-DbaDbUser @userParam -Force + $null = Remove-DbaDbUser @userParam -Force } catch { Stop-Function -Message "Could not remove existing user [$Username] in the database $dbSmo on [$instance], skipping." -Target $User -ErrorRecord $_ -Continue } diff --git a/public/New-DbaDirectory.ps1 b/public/New-DbaDirectory.ps1 index 7e5c21090a..67ed171cad 100644 --- a/public/New-DbaDirectory.ps1 +++ b/public/New-DbaDirectory.ps1 @@ -93,7 +93,7 @@ function New-DbaDirectory { Stop-Function -Message "Failure" -ErrorRecord $_ } - [pscustomobject]@{ + [PSCustomObject]@{ Server = $instance Path = $Path Created = $created diff --git a/public/New-DbaEndpoint.ps1 b/public/New-DbaEndpoint.ps1 index 0f7aa9c340..45256131dc 100644 --- a/public/New-DbaEndpoint.ps1 +++ b/public/New-DbaEndpoint.ps1 @@ -97,7 +97,7 @@ function New-DbaEndpoint { PS C:\> New-DbaEndpoint -SqlInstance localhost\sql2017 -Type DatabaseMirroring -IPAddress 192.168.0.15 -Port 5055 Creates a database mirroring endpoint on localhost\sql2017 which binds only on ipaddress 192.168.0.15 and port 5055 - #> + #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')] param ( [parameter(Mandatory, ValueFromPipeline)] diff --git a/public/New-DbaReplCreationScriptOptions.ps1 b/public/New-DbaReplCreationScriptOptions.ps1 new file mode 100644 index 0000000000..20edf0629c --- /dev/null +++ b/public/New-DbaReplCreationScriptOptions.ps1 @@ -0,0 +1,80 @@ +function New-DbaReplCreationScriptOptions { + <# + .SYNOPSIS + Creates a new Microsoft.SqlServer.Replication.CreationScriptOptions enumeration object. + + .DESCRIPTION + Creates a new Microsoft.SqlServer.Replication.CreationScriptOptions enumeration object that allows you to specify article options. + + See https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.replication.creationscriptoptions for more information + + .PARAMETER Options + The options to set on published articles. + See https://docs.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.replication.creationscriptoptions for a list of available options + + .PARAMETER NoDefaults + If specified, no default options will be set on the object + + Defaults are copied from when you add an article in SQL Server Management Studio and include: + PrimaryObject, CustomProcedures, Identity, KeepTimestamp, + ClusteredIndexes, DriPrimaryKey, Collation, DriUniqueKeys, + MarkReplicatedCheckConstraintsAsNotForReplication, + MarkReplicatedForeignKeyConstraintsAsNotForReplication, and Schema + + .NOTES + Tags: repl, Replication, Script + Author: Jess Pomfret (@jpomfret), jesspomfret.com + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/New-DbaReplCreationScriptOptions + + .EXAMPLE + PS C:\> $cso = New-DbaReplCreationScriptOptions -Options NonClusteredIndexes, Statistics + PS C:\> $article = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'testPub' + Name = 'stores' + CreationScriptOptions = $cso + } + Add-DbaReplArticle @article -EnableException + + Adds the stores table to the testPub publication from mssql1.pubs with the NonClusteredIndexes and Statistics options set + includes default options. + + + .EXAMPLE + PS C:\> $cso = New-DbaReplCreationScriptOptions -Options ClusteredIndexes, Identity -NoDefaults + PS C:\> $article = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'testPub' + Name = 'stores' + CreationScriptOptions = $cso + } + Add-DbaReplArticle @article -EnableException + + Adds the stores table to the testPub publication from mssql1.pubs with the ClusteredIndexes and Identity options set, excludes default options. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] + param ( + [String[]]$Options, + [switch]$NoDefaults + ) + + $cso = New-Object Microsoft.SqlServer.Replication.CreationScriptOptions + + if (-not $NoDefaults) { + 'PrimaryObject', 'CustomProcedures', 'Identity', 'KeepTimestamp', 'ClusteredIndexes', 'DriPrimaryKey', 'Collation', 'DriUniqueKeys', 'MarkReplicatedCheckConstraintsAsNotForReplication', 'MarkReplicatedForeignKeyConstraintsAsNotForReplication', 'Schema' | ForEach-Object { $cso += $_ } + } + + foreach ($opt in $options) { + $cso += $opt + } + + $cso +} \ No newline at end of file diff --git a/public/New-DbaReplPublication.ps1 b/public/New-DbaReplPublication.ps1 new file mode 100644 index 0000000000..7c538626fc --- /dev/null +++ b/public/New-DbaReplPublication.ps1 @@ -0,0 +1,200 @@ +function New-DbaReplPublication { + <# + .SYNOPSIS + Creates a publication for the database on the target SQL instances. + + .DESCRIPTION + Creates a publication for the database on the target SQL instances. + + https://learn.microsoft.com/en-us/sql/relational-databases/replication/publish/create-a-publication?view=sql-server-ver16 + + .PARAMETER SqlInstance + The target SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER Database + The database that contains the articles to be replicated. + + .PARAMETER Name + The name of the replication publication. + + .PARAMETER Type + The flavour of replication. + Options are Transactional, Snapshot, Merge + + .PARAMETER LogReaderAgentCredential + Used to provide the credentials for the Microsoft Windows account under which the Log Reader Agent runs + + Setting LogReaderAgentProcessSecurity is not required when the publication is created by a member of the sysadmin fixed server role. + In this case, the agent will impersonate the SQL Server Agent account. For more information, see Replication Agent Security Model. + + TODO: test LogReaderAgentCredential parameters + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .PARAMETER WhatIf + If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. + + .PARAMETER Confirm + If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. + + .NOTES + Tags: repl, Replication + Author: Jess Pomfret (@jpomfret), jesspomfret.com + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/New-DbaReplPublication + + .EXAMPLE + PS C:\> New-DbaReplPublication -SqlInstance mssql1 -Database Northwind -Name PubFromPosh -Type Transactional + + Creates a transactional publication called PubFromPosh for the Northwind database on mssql1 + + .EXAMPLE + PS C:\> New-DbaReplPublication -SqlInstance mssql1 -Database pubs -Name snapPub -Type Snapshot + + Creates a snapshot publication called snapPub for the pubs database on mssql1 + + .EXAMPLE + PS C:\> New-DbaReplPublication -SqlInstance mssql1 -Database pubs -Name mergePub -Type Merge + + Creates a merge publication called mergePub for the pubs database on mssql1 + #> + [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess, ConfirmImpact = 'Medium')] + param ( + [parameter(Mandatory, ValueFromPipeline)] + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [parameter(Mandatory)] + [String]$Database, + [parameter(Mandatory)] + [String]$Name, + [parameter(Mandatory)] + [ValidateSet("Snapshot", "Transactional", "Merge")] + [String]$Type, + [PSCredential]$LogReaderAgentCredential, + [Switch]$EnableException + ) + process { + foreach ($instance in $SqlInstance) { + try { + $replServer = Get-DbaReplServer -SqlInstance $instance -SqlCredential $SqlCredential -EnableException:$EnableException + + if (-not $replServer.IsPublisher) { + Stop-Function -Message "Instance $instance is not a publisher, run Enable-DbaReplPublishing to set this up" -Target $instance -Continue + } + + } catch { + Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue + } + Write-Message -Level Verbose -Message "Creating publication on $instance" + + try { + if ($PSCmdlet.ShouldProcess($instance, "Creating publication on $instance")) { + + + + $pubDatabase = New-Object Microsoft.SqlServer.Replication.ReplicationDatabase + $pubDatabase.ConnectionContext = $replServer.ConnectionContext + $pubDatabase.Name = $Database + if (-not $pubDatabase.LoadProperties()) { + throw "Database $Database not found on $instance" + } + + if ($Type -in ('Transactional', 'Snapshot')) { + Write-Message -Level Verbose -Message "Enable trans publishing publication on $instance.$Database" + $pubDatabase.EnabledTransPublishing = $true + $pubDatabase.CommitPropertyChanges() + # log reader agent is only needed for transactional and snapshot replication. + if (-not $pubDatabase.LogReaderAgentExists) { + Write-Message -Level Verbose -Message "Create log reader agent job for $Database on $instance" + if ($LogReaderAgentCredential) { + $pubDatabase.LogReaderAgentProcessSecurity.Login = $LogReaderAgentCredential.UserName + $pubDatabase.LogReaderAgentProcessSecurity.Password = $LogReaderAgentCredential.Password + } + + #(Optional) Set the SqlStandardLogin and SqlStandardPassword or + # SecureSqlStandardPassword fields of LogReaderAgentPublisherSecurity when using SQL Server Authentication to connect to the Publisher. + + $pubDatabase.CreateLogReaderAgent() + } else { + Write-Message -Level Verbose -Message "Log reader agent job already exists for $Database on $instance" + } + + } elseif ($Type -eq 'Merge') { + Write-Message -Level Verbose -Message "Enable merge publishing publication on $instance.$Database" + $pubDatabase.EnabledMergePublishing = $true + $pubDatabase.CommitPropertyChanges() + } + + if ($Type -in ('Transactional', 'Snapshot')) { + + $transPub = New-Object Microsoft.SqlServer.Replication.TransPublication + $transPub.ConnectionContext = $replServer.ConnectionContext + $transPub.DatabaseName = $Database + $transPub.Name = $Name + $transPub.Type = $Type + $transPub.Create() + + # create the Snapshot Agent job + $transPub.CreateSnapshotAgent() + + <# + TODO: add SnapshotGenerationAgentProcessSecurity creds in? + + The Login and Password fields of SnapshotGenerationAgentProcessSecurity to provide the credentials for the Windows account under which the Snapshot Agent runs. + This account is also used when the Snapshot Agent makes connections to the local Distributor and for any remote connections when using Windows Authentication. + + Note + Setting SnapshotGenerationAgentProcessSecurity is not required when the publication is created by a member of the sysadmin fixed server role. + In this case, the agent will impersonate the SQL Server Agent account. For more information, see Replication Agent Security Model. + + (Optional) The SqlStandardLogin and SqlStandardPassword or + SecureSqlStandardPassword fields of SnapshotGenerationAgentPublisherSecurity when using SQL Server Authentication to connect to the Publisher. + #> + } elseif ($Type -eq 'Merge') { + $mergePub = New-Object Microsoft.SqlServer.Replication.MergePublication + $mergePub.ConnectionContext = $replServer.ConnectionContext + $mergePub.DatabaseName = $Database + $mergePub.Name = $Name + $mergePub.Create() + + # create the Snapshot Agent job + $mergePub.CreateSnapshotAgent() + + <# + TODO: add SnapshotGenerationAgentProcessSecurity creds in? + + The Login and Password fields of SnapshotGenerationAgentProcessSecurity to provide the credentials for the Windows account under which the Snapshot Agent runs. + This account is also used when the Snapshot Agent makes connections to the local Distributor and for any remote connections when using Windows Authentication. + + Note + Setting SnapshotGenerationAgentProcessSecurity is not required when the publication is created by a member of the sysadmin fixed server role. + For more information, see Replication Agent Security Model. + + (Optional) Use the inclusive logical OR operator (| in Visual C# and Or in Visual Basic) and the exclusive logical OR operator (^ in Visual C# and Xor in Visual Basic) + to set the PublicationAttributes values for the Attributes property. + + #> + } + } + } catch { + Stop-Function -Message ("Unable to create publication - {0}" -f $_) -ErrorRecord $_ -Target $instance -Continue + } + Get-DbaRepPublication -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database -Name $Name + } + } +} \ No newline at end of file diff --git a/public/New-DbaReplSubscription.ps1 b/public/New-DbaReplSubscription.ps1 new file mode 100644 index 0000000000..37ffff9b25 --- /dev/null +++ b/public/New-DbaReplSubscription.ps1 @@ -0,0 +1,300 @@ +function New-DbaReplSubscription { + <# + .SYNOPSIS + Creates a subscription for the database on the target SQL instances. + + .DESCRIPTION + Creates a subscription for the database on the target SQL instances. + + .PARAMETER SqlInstance + The target publishing SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target publishing instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER Database + The database on the publisher that will be replicated. + + .PARAMETER SubscriberSqlInstance + The subscriber SQL instance. + + .PARAMETER SubscriberSqlCredential + Login to the subscriber instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER SubscriptionDatabase + The database on the subscriber that will be the target of the replicated data. + + .PARAMETER PublicationName + The name of the replication publication + + .PARAMETER SubscriptionSqlCredential + Credential object that will be saved as the 'subscriber credential' in the subscription properties. + + .PARAMETER Type + The flavour of the subscription. Push or Pull. + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .PARAMETER WhatIf + If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. + + .PARAMETER Confirm + If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. + + .NOTES + Tags: repl, Replication + Author: Jess Pomfret (@jpomfret), jesspomfret.com + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/New-DbaReplSubscription + + .EXAMPLE + PS C:\> New-DbaReplSubscription -SqlInstance sql2017 -Database pubs -SubscriberSqlInstance sql2019 -SubscriptionDatabase pubs -PublicationName testPub -Type Push + + Creates a push subscription from sql2017 to sql2019 for the pubs database. + + .EXAMPLE + PS C:\> New-DbaReplSubscription -SqlInstance sql2017 -Database pubs -SubscriberSqlInstance sql2019 -SubscriptionDatabase pubs -PublicationName testPub -Type Pull + + Creates a pull subscription from sql2017 to sql2019 for the pubs database. + #> + [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess, ConfirmImpact = 'Medium')] + param ( + [Parameter(Mandatory, ValueFromPipeline)] + [DbaInstanceParameter]$SqlInstance, + [PSCredential]$SqlCredential, + [String]$Database, + [Parameter(Mandatory)] + [DbaInstanceParameter[]]$SubscriberSqlInstance, + [PSCredential]$SubscriberSqlCredential, + [String]$SubscriptionDatabase, + [Parameter(Mandatory)] + [String]$PublicationName, + [PSCredential] + $SubscriptionSqlCredential, + [Parameter(Mandatory)] + [ValidateSet("Push", "Pull")] + [String]$Type, + [Switch]$EnableException + ) + begin { + Write-Message -Level Verbose -Message "Connecting to publisher: $SqlInstance" + + # connect to publisher and get the publication + try { + $pubReplServer = Get-DbaReplServer -SqlInstance $SqlInstance -SqlCredential $SqlCredential -EnableException:$EnableException + } catch { + Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $SqlInstance -Continue + } + + try { + $pub = Get-DbaReplPublication -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Name $PublicationName -EnableException:$EnableException + } catch { + Stop-Function -Message ("Publication {0} not found on {1}" -f $PublicationName, $SqlInstance) -ErrorRecord $_ -Target $SqlInstance -Continue + } + } + + process { + + # for each subscription SqlInstance we need to create a subscription + foreach ($instance in $SubscriberSqlInstance) { + + try { + $subReplServer = Get-DbaReplServer -SqlInstance $instance -SqlCredential $SubscriberSqlCredential -EnableException:$EnableException + + if (-not (Get-DbaDatabase -SqlInstance $instance -SqlCredential $SubscriberSqlCredential -Database $SubscriptionDatabase -EnableException:$EnableException)) { + + Write-Message -Level Verbose -Message "Subscription database $SubscriptionDatabase not found on $instance - will create it - but you should check the settings!" + + if ($PSCmdlet.ShouldProcess($instance, "Creating subscription database")) { + + $newSubDb = @{ + SqlInstance = $instance + SqlCredential = $SubscriberSqlCredential + Name = $SubscriptionDatabase + EnableException = $EnableException + } + $null = New-DbaDatabase @newSubDb + } + } + } catch { + Stop-Function -Message ("Couldn't create the subscription database {0}.{1}" -f $instance, $SubscriptionDatabase) -ErrorRecord $_ -Target $instance -Continue + } + + try { + Write-Message -Level Verbose -Message "Creating subscription on $instance" + if ($PSCmdlet.ShouldProcess($instance, "Creating subscription on $instance")) { + + # check if needed schemas exist + foreach ($schema in $pub.articles.DestinationObjectOwner) { + if ($schema -ne 'dbo' -and -not (Get-DbaDbSchema -SqlInstance $instance -SqlCredential $SubscriberSqlCredential -Database $SubscriptionDatabase -Schema $schema)) { + Write-Message -Level Verbose -Message "Subscription database $SubscriptionDatabase does not contain the $schema schema on $instance - will create it!" + $null = New-DbaDbSchema -SqlInstance $instance -SqlCredential $SubscriberSqlCredential -Database $SubscriptionDatabase -Schema $schema -EnableException + } + } + + if ($pub.Type -in ('Transactional', 'Snapshot')) { + + $transPub = New-Object Microsoft.SqlServer.Replication.TransPublication + $transPub.ConnectionContext = $pubReplServer.ConnectionContext + $transPub.DatabaseName = $Database + $transPub.Name = $PublicationName + + # if LoadProperties returns then the publication was found + if ( $transPub.LoadProperties() ) { + + if ($type -eq 'Push') { + + # Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPush. + if (($transPub.Attributes -band [Microsoft.SqlServer.Replication.PublicationAttributes]::AllowPush) -ne [Microsoft.SqlServer.Replication.PublicationAttributes]::AllowPush) { + + # # Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPush. + # if ($transPub.Attributes -band 'AllowPush' -eq 'None' ) { + + # If the result is None, set Attributes to the result of a bitwise logical OR (| in Visual C# and Or in Visual Basic) between Attributes and AllowPush. + $transPub.Attributes = $transPub.Attributes -bor 'AllowPush' + + # Then, call CommitPropertyChanges to enable push subscriptions. + $transPub.CommitPropertyChanges() + } + } else { + #TODO: Fix pull subscriptions in New-DbaReplSubscription command - this still creates a PUSH + + # Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPull. + if (($transPub.Attributes -band [Microsoft.SqlServer.Replication.PublicationAttributes]::AllowPull) -ne [Microsoft.SqlServer.Replication.PublicationAttributes]::AllowPull) { + # If the result is None, set Attributes to the result of a bitwise logical OR (| in Visual C# and Or in Visual Basic) between Attributes and AllowPull. + $transPub.Attributes = $transPub.Attributes -bor 'AllowPull' + + # Then, call CommitPropertyChanges to enable pull subscriptions. + $transPub.CommitPropertyChanges() + } + } + + # create the subscription + $transSub = New-Object Microsoft.SqlServer.Replication.TransSubscription + $transSub.ConnectionContext = $pubReplServer.ConnectionContext + $transSub.SubscriptionDBName = $SubscriptionDatabase + $transSub.SubscriberName = $instance + $transSub.DatabaseName = $Database + $transSub.PublicationName = $PublicationName + + #TODO: + + <# + The Login and Password fields of SynchronizationAgentProcessSecurity to provide the credentials for the + Microsoft Windows account under which the Distribution Agent runs at the Distributor. This account is used to make local connections to the Distributor and to make + remote connections by using Windows Authentication. + + Note + Setting SynchronizationAgentProcessSecurity is not required when the subscription is created by a member of the sysadmin fixed server role, but we recommend it. + In this case, the agent will impersonate the SQL Server Agent account. For more information, see Replication Agent security model. + + (Optional) A value of true (the default) for CreateSyncAgentByDefault to create an agent job that is used to synchronize the subscription. + If you specify false, the subscription can only be synchronized programmatically. + + #> + + if ($SubscriptionSqlCredential) { + $transSub.SubscriberSecurity.WindowsAuthentication = $false + $transSub.SubscriberSecurity.SqlStandardLogin = $SubscriptionSqlCredential.UserName + $transSub.SubscriberSecurity.SecureSqlStandardPassword = $SubscriptionSqlCredential.Password + } + + $transSub.Create() + } else { + Stop-Function -Message ("Publication {0} not found on {1}" -f $PublicationName, $instance) -ErrorRecord $_ -Target $instance -Continue + } + + } elseif ($pub.Type -eq 'Merge') { + + $mergePub = New-Object Microsoft.SqlServer.Replication.MergePublication + $mergePub.ConnectionContext = $pubReplServer.ConnectionContext + $mergePub.DatabaseName = $Database + $mergePub.Name = $PublicationName + + if ( $mergePub.LoadProperties() ) { + + if ($type = 'Push') { + # Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPush. + if ($mergePub.Attributes -band 'AllowPush' -eq 'None' ) { + # If the result is None, set Attributes to the result of a bitwise logical OR (| in Visual C# and Or in Visual Basic) between Attributes and AllowPush. + $mergePub.Attributes = $mergePub.Attributes -bor 'AllowPush' + + # Then, call CommitPropertyChanges to enable push subscriptions. + $mergePub.CommitPropertyChanges() + } + + } else { + # Perform a bitwise logical AND (& in Visual C# and And in Visual Basic) between the Attributes property and AllowPull. + if ($mergePub.Attributes -band 'AllowPull' -eq 'None' ) { + # If the result is None, set Attributes to the result of a bitwise logical OR (| in Visual C# and Or in Visual Basic) between Attributes and AllowPull. + $mergePub.Attributes = $mergePub.Attributes -bor 'AllowPull' + + # Then, call CommitPropertyChanges to enable pull subscriptions. + $mergePub.CommitPropertyChanges() + } + } + + # create the subscription + if ($type = 'Push') { + $mergeSub = New-Object Microsoft.SqlServer.Replication.MergeSubscription + } else { + $mergeSub = New-Object Microsoft.SqlServer.Replication.MergePullSubscription + } + + $mergeSub.ConnectionContext = $pubReplServer.ConnectionContext + $mergeSub.SubscriptionDBName = $SubscriptionDatabase + $mergeSub.SubscriberName = $instance + $mergeSub.DatabaseName = $Database + $mergeSub.PublicationName = $PublicationName + + #TODO: + + <# + The Login and Password fields of SynchronizationAgentProcessSecurity to provide the credentials for the + Microsoft Windows account under which the Distribution Agent runs at the Distributor. This account is used to make local connections to the Distributor and to make + remote connections by using Windows Authentication. + + Note + Setting SynchronizationAgentProcessSecurity is not required when the subscription is created by a member of the sysadmin fixed server role, but we recommend it. + In this case, the agent will impersonate the SQL Server Agent account. For more information, see Replication Agent security model. + + (Optional) A value of true (the default) for CreateSyncAgentByDefault to create an agent job that is used to synchronize the subscription. + If you specify false, the subscription can only be synchronized programmatically. + + #> + if ($SubscriptionSqlCredential) { + $mergeSub.SubscriberSecurity.WindowsAuthentication = $false + $mergeSub.SubscriberSecurity.SqlStandardLogin = $SubscriptionSqlCredential.UserName + $mergeSub.SubscriberSecurity.SecureSqlStandardPassword = $SubscriptionSqlCredential.Password + } + + $mergeSub.Create() + } + + } else { + Stop-Function -Message ("Publication {0} not found on {1}" -f $PublicationName, $instance) -ErrorRecord $_ -Target $instance -Continue + } + } + } catch { + Stop-Function -Message ("Unable to create subscription - {0}" -f $_) -ErrorRecord $_ -Target $instance -Continue + } + #TODO: call Get-DbaReplSubscription when it's done + } + } +} \ No newline at end of file diff --git a/public/New-DbaSsisCatalog.ps1 b/public/New-DbaSsisCatalog.ps1 index 2e2a16e024..63c764e9e3 100644 --- a/public/New-DbaSsisCatalog.ps1 +++ b/public/New-DbaSsisCatalog.ps1 @@ -148,7 +148,7 @@ function New-DbaSsisCatalog { } try { $ssisdb.Create() - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/New-DbaXESmartEmail.ps1 b/public/New-DbaXESmartEmail.ps1 index d497772b5e..52690a2192 100644 --- a/public/New-DbaXESmartEmail.ps1 +++ b/public/New-DbaXESmartEmail.ps1 @@ -98,7 +98,7 @@ function New-DbaXESmartEmail { [string[]]$To, [string[]]$Cc, [string[]]$Bcc, - [pscredential]$Credential, + [PSCredential]$Credential, [parameter(Mandatory)] [string]$Subject, [parameter(Mandatory)] diff --git a/public/New-DbatoolsSupportPackage.ps1 b/public/New-DbatoolsSupportPackage.ps1 index a3e75c5b44..6e1348b874 100644 --- a/public/New-DbatoolsSupportPackage.ps1 +++ b/public/New-DbatoolsSupportPackage.ps1 @@ -169,7 +169,7 @@ Ideally start a new console, perform the minimal steps required to reproduce the $hash["Variables"] = $Variables | Get-Variable -ErrorAction Ignore } - $data = [pscustomobject]$hash + $data = [PSCustomObject]$hash try { $data | Export-Clixml -Path $filePathXml -ErrorAction Stop diff --git a/public/Publish-DbaDacPackage.ps1 b/public/Publish-DbaDacPackage.ps1 index 82cd734293..94d641cc32 100644 --- a/public/Publish-DbaDacPackage.ps1 +++ b/public/Publish-DbaDacPackage.ps1 @@ -331,7 +331,7 @@ function Publish-DbaDacPackage { $server = [dbainstance]$instance if ($Type -eq 'Dacpac') { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.InstanceName SqlInstance = $server.FullName @@ -347,7 +347,7 @@ function Publish-DbaDacPackage { SqlCmdVariableValues = $options.DeployOptions.SqlCommandVariableValues.Keys } } elseif ($Type -eq 'Bacpac') { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.InstanceName SqlInstance = $server.FullName diff --git a/public/Read-DbaAuditFile.ps1 b/public/Read-DbaAuditFile.ps1 index c06be296f8..ff39981839 100644 --- a/public/Read-DbaAuditFile.ps1 +++ b/public/Read-DbaAuditFile.ps1 @@ -125,7 +125,7 @@ function Read-DbaAuditFile { $hash[$key] = $event.Fields[$key] } - [pscustomobject]$hash + [PSCustomObject]$hash } } } diff --git a/public/Read-DbaBackupHeader.ps1 b/public/Read-DbaBackupHeader.ps1 index d9b1d747d8..7b237a57ac 100644 --- a/public/Read-DbaBackupHeader.ps1 +++ b/public/Read-DbaBackupHeader.ps1 @@ -92,7 +92,7 @@ function Read-DbaBackupHeader { param ( [parameter(Mandatory)] [DbaInstance]$SqlInstance, - [PsCredential]$SqlCredential, + [PSCredential]$SqlCredential, [parameter(Mandatory, ValueFromPipeline)] [object[]]$Path, [switch]$Simple, @@ -222,7 +222,7 @@ function Read-DbaBackupHeader { $thread.AddParameters($argsRunPool) | Out-Null #Start the thread $handle = $thread.BeginInvoke() - $threads += [pscustomobject]@{ + $threads += [PSCustomObject]@{ handle = $handle thread = $thread file = $file diff --git a/public/Read-DbaXEFile.ps1 b/public/Read-DbaXEFile.ps1 index e211da1bcb..cd87b6c804 100644 --- a/public/Read-DbaXEFile.ps1 +++ b/public/Read-DbaXEFile.ps1 @@ -6,11 +6,15 @@ function Read-DbaXEFile { .DESCRIPTION Read XEvents from a *.xel or *.xem file. + The file that the XESession is currently writing to can not be accessed and will be skipped using pipeline input from Get-DbaXESession. + .PARAMETER Path The path to the *.xem or *.xem file. This is relative to the computer executing the command. UNC paths are supported. + Piping from Get-DbaXESession is also supported. + .PARAMETER Raw - If this switch is enabled, the Microsoft.SqlServer.XEvent.Linq.PublishedEvent enumeration object will be returned. + If this switch is enabled, an array of Microsoft.SqlServer.XEvent.XELite.XEvent objects will be returned. .PARAMETER EnableException By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. @@ -39,7 +43,7 @@ function Read-DbaXEFile { Returns events from all .xel files in C:\temp\xe. .EXAMPLE - PS C:\> Get-DbaXESession -SqlInstance sql2014 -Session deadlocks | Read-DbaXEFile + PS C:\> Get-DbaXESession -SqlInstance sql2019 -Session deadlocks | Read-DbaXEFile Reads remote XEvents by accessing the file over the admin UNC share. @@ -54,83 +58,87 @@ function Read-DbaXEFile { ) process { if (Test-FunctionInterrupt) { return } - foreach ($file in $path) { + foreach ($pathObject in $Path) { # in order to ensure CSV gets all fields, all columns will be # collected and output in the first (all all subsequent) object $columns = @("name", "timestamp") - if ($file -is [System.String]) { - $currentfile = $file - #Variable marked as unused by PSScriptAnalyzer - #$manualadd = $true - } elseif ($file -is [System.IO.FileInfo]) { - $currentfile = $file.FullName - #Variable marked as unused by PSScriptAnalyzer - #$manualadd = $true - } else { - if ($file -isnot [Microsoft.SqlServer.Management.XEvent.Session]) { - Stop-Function -Message "Unsupported file type." - return - } - - if ($file.TargetFile.Length -eq 0) { - Stop-Function -Message "This session does not have an associated Target File." - return + if ($pathObject -is [System.String]) { + $files = $pathObject + } elseif ($pathObject -is [System.IO.FileInfo]) { + $files = $pathObject.FullName + } elseif ($pathObject -is [Microsoft.SqlServer.Management.XEvent.Session]) { + if ($pathObject.TargetFile.Length -eq 0) { + Stop-Function -Message "The session [$pathObject] does not have an associated Target File." -Continue } - $instance = [dbainstance]$file.ComputerName - + $instance = [DbaInstance]$pathObject.ComputerName if ($instance.IsLocalHost) { - $currentfile = $file.TargetFile + $targetFile = $pathObject.TargetFile } else { - $currentfile = $file.RemoteTargetFile + $targetFile = $pathObject.RemoteTargetFile } - } - - $accessible = Test-Path -Path $currentfile - $whoami = whoami - if (-not $accessible) { - if ($file.Status -eq "Stopped") { continue } - Stop-Function -Continue -Message "$currentfile cannot be accessed from $($env:COMPUTERNAME). Does $whoami have access?" - } - - if ($Raw) { - return (SqlServer.XEvent\Read-SqlXEvent -FileName $currentfile) - } - - # use the SqlServer.XEvent\Read-SqlXEvent cmdlet from Microsoft - # because the underlying Class uses Tasks - # which is hard to handle in PowerShell - - $enum = SqlServer.XEvent\Read-SqlXEvent -FileName $currentfile - $newcolumns = ($enum.Fields.Name | Select-Object -Unique) - - $actions = ($enum.Actions.Name | Select-Object -Unique) - foreach ($action in $actions) { - $newcolumns += ($action -Split '\.')[-1] + $targetFile = $targetFile.Replace('.xel', '*.xel').Replace('.xem', '*.xem') + $files = Get-ChildItem -Path $targetFile | Sort-Object LastWriteTime + if ($pathObject.Status -eq 'Running') { + $files = $files | Select-Object -SkipLast 1 + } + Write-Message -Level Verbose -Message "Received $($files.Count) files based on [$targetFile]" + } else { + Stop-Function -Message "The Path [$pathObject] has an unsupported file type of [$($pathObject.GetType().FullName)]." } - $newcolumns = $newcolumns | Sort-Object - $columns = ($columns += $newcolumns) | Select-Object -Unique - - # Make it selectable, otherwise it's a weird enumeration - foreach ($event in $enum) { - $hash = [ordered]@{ } - - foreach ($column in $columns) { - $null = $hash.Add($column, $event.$column) + foreach ($file in $files) { + if (-not (Test-Path -Path $file)) { + Stop-Function -Message "$file cannot be accessed from $($env:COMPUTERNAME)." -Continue } - foreach ($key in $event.Actions.Keys) { - $hash[$key] = $event.Actions[$key] - } + # use the SqlServer\Read-SqlXEvent cmdlet from Microsoft + # because the underlying Class uses Tasks + # which is hard to handle in PowerShell - foreach ($key in $event.Fields.Keys) { - $hash[$key] = $event.Fields[$key] + if ($Raw) { + try { + Read-XEvent -FileName $file + } catch { + Stop-Function -Message "Failure" -ErrorRecord $_ -Target $file -Continue + } + } else { + try { + $enum = Read-XEvent -FileName $file + } catch { + Stop-Function -Message "Failure" -ErrorRecord $_ -Target $file -Continue + } + $newcolumns = ($enum.Fields.Name | Select-Object -Unique) + + $actions = ($enum.Actions.Name | Select-Object -Unique) + foreach ($action in $actions) { + $newcolumns += ($action -Split '\.')[-1] + } + + $newcolumns = $newcolumns | Sort-Object + $columns = ($columns += $newcolumns) | Select-Object -Unique + + # Make it selectable, otherwise it's a weird enumeration + foreach ($event in $enum) { + $hash = [ordered]@{ } + + foreach ($column in $columns) { + $null = $hash.Add($column, $event.$column) + } + + foreach ($key in $event.Actions.Keys) { + $hash[$key] = $event.Actions[$key] + } + + foreach ($key in $event.Fields.Keys) { + $hash[$key] = $event.Fields[$key] + } + + [PSCustomObject]$hash + } } - - [pscustomobject]$hash } } } diff --git a/public/Remove-DbaAgDatabase.ps1 b/public/Remove-DbaAgDatabase.ps1 index 83e4d1e43d..cd815c6826 100644 --- a/public/Remove-DbaAgDatabase.ps1 +++ b/public/Remove-DbaAgDatabase.ps1 @@ -102,7 +102,7 @@ function Remove-DbaAgDatabase { try { $ag = $db.Parent.Name $db.Parent.AvailabilityDatabases[$db.Name].Drop() - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $db.ComputerName InstanceName = $db.InstanceName SqlInstance = $db.SqlInstance @@ -116,4 +116,4 @@ function Remove-DbaAgDatabase { } } } -} +} \ No newline at end of file diff --git a/public/Remove-DbaAgListener.ps1 b/public/Remove-DbaAgListener.ps1 index e5043a0693..a83ff4b5c7 100644 --- a/public/Remove-DbaAgListener.ps1 +++ b/public/Remove-DbaAgListener.ps1 @@ -89,7 +89,7 @@ function Remove-DbaAgListener { try { $ag = $aglistener.Parent.Name $aglistener.Parent.AvailabilityGroupListeners[$aglistener.Name].Drop() - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $aglistener.ComputerName InstanceName = $aglistener.InstanceName SqlInstance = $aglistener.SqlInstance diff --git a/public/Remove-DbaAgReplica.ps1 b/public/Remove-DbaAgReplica.ps1 index ae5706f58c..5cacb8613d 100644 --- a/public/Remove-DbaAgReplica.ps1 +++ b/public/Remove-DbaAgReplica.ps1 @@ -86,7 +86,7 @@ function Remove-DbaAgReplica { if ($Pscmdlet.ShouldProcess($agreplica.Parent.Parent.Name, "Removing availability group replica $agreplica")) { try { $agreplica.Drop() - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $agreplica.ComputerName InstanceName = $agreplica.InstanceName SqlInstance = $agreplica.SqlInstance diff --git a/public/Remove-DbaAgentAlert.ps1 b/public/Remove-DbaAgentAlert.ps1 index 7591d8a5b2..eeef214755 100644 --- a/public/Remove-DbaAgentAlert.ps1 +++ b/public/Remove-DbaAgentAlert.ps1 @@ -98,7 +98,7 @@ function Remove-DbaAgentAlert { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaAgentAlert. foreach ($dbAlert in $dbAlerts) { if ($PSCmdlet.ShouldProcess($dbAlert.Parent.Parent.Name, "Removing the SQL Agent alert $($dbAlert.Name) on $($dbAlert.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $dbAlert.Parent.Parent.ComputerName InstanceName = $dbAlert.Parent.Parent.ServiceName SqlInstance = $dbAlert.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaAgentAlertCategory.ps1 b/public/Remove-DbaAgentAlertCategory.ps1 index c429171d4c..e0f5fe7193 100644 --- a/public/Remove-DbaAgentAlertCategory.ps1 +++ b/public/Remove-DbaAgentAlertCategory.ps1 @@ -99,7 +99,7 @@ function Remove-DbaAgentAlertCategory { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaAgentAlertCategory. foreach ($agentCategory in $agentCategories) { if ($PSCmdlet.ShouldProcess($agentCategory.Parent.Parent.Name, "Removing the SQL Agent alert category $($agentCategory.Name) on $($agentCategory.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $agentCategory.Parent.Parent.ComputerName InstanceName = $agentCategory.Parent.Parent.ServiceName SqlInstance = $agentCategory.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaAgentJob.ps1 b/public/Remove-DbaAgentJob.ps1 index c128d7ce4a..c447fdd736 100644 --- a/public/Remove-DbaAgentJob.ps1 +++ b/public/Remove-DbaAgentJob.ps1 @@ -133,7 +133,7 @@ function Remove-DbaAgentJob { $server.Databases['msdb'].ExecuteNonQuery($dropJobQuery) $server.JobServer.Jobs.Refresh() Remove-TeppCacheItem -SqlInstance $server -Type job -Name $currentJob.Name - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -143,7 +143,7 @@ function Remove-DbaAgentJob { } catch { Write-Message -Level Verbose -Message "Could not drop job $job on $server" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Remove-DbaAgentJobCategory.ps1 b/public/Remove-DbaAgentJobCategory.ps1 index a1ef3d17f4..cd07d1da02 100644 --- a/public/Remove-DbaAgentJobCategory.ps1 +++ b/public/Remove-DbaAgentJobCategory.ps1 @@ -106,7 +106,7 @@ function Remove-DbaAgentJobCategory { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaAgentJobCategory. foreach ($jobCategory in $jobCategories) { if ($PSCmdlet.ShouldProcess($jobCategory.Parent.Parent.Name, "Removing the SQL Agent category(-ies) $($jobCategory.Name) on $($jobCategory.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $jobCategory.Parent.Parent.ComputerName InstanceName = $jobCategory.Parent.Parent.ServiceName SqlInstance = $jobCategory.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaAgentOperator.ps1 b/public/Remove-DbaAgentOperator.ps1 index 04de19b778..ced4c2dc9c 100644 --- a/public/Remove-DbaAgentOperator.ps1 +++ b/public/Remove-DbaAgentOperator.ps1 @@ -92,7 +92,7 @@ function Remove-DbaAgentOperator { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaAgentOperator. foreach ($dbOperator in $dbOperators) { if ($PSCmdlet.ShouldProcess($dbOperator.Parent.Parent.Name, "Removing the SQL Agent operator $($dbOperator.Name) on $($dbOperator.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $dbOperator.Parent.Parent.ComputerName InstanceName = $dbOperator.Parent.Parent.ServiceName SqlInstance = $dbOperator.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaAgentProxy.ps1 b/public/Remove-DbaAgentProxy.ps1 index ac156af770..44be24e82c 100644 --- a/public/Remove-DbaAgentProxy.ps1 +++ b/public/Remove-DbaAgentProxy.ps1 @@ -94,7 +94,7 @@ function Remove-DbaAgentProxy { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaAgentProxy. foreach ($dbProxy in $dbProxies) { if ($PSCmdlet.ShouldProcess($dbProxy.Parent.Parent.Name, "Removing the SQL Agent proxy $($dbProxy.Name) on $($dbProxy.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $dbProxy.Parent.Parent.ComputerName InstanceName = $dbProxy.Parent.Parent.ServiceName SqlInstance = $dbProxy.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaAgentSchedule.ps1 b/public/Remove-DbaAgentSchedule.ps1 index f3343ba6f3..3aaba51faa 100644 --- a/public/Remove-DbaAgentSchedule.ps1 +++ b/public/Remove-DbaAgentSchedule.ps1 @@ -129,7 +129,7 @@ function Remove-DbaAgentSchedule { Stop-Function -Message "The schedule $($sched.Name) with id $($sched.Id) and uid $($sched.ScheduleUid) is used in one or more jobs. If removal is neccesary use -Force." -Target $sched.Parent.Parent -Continue } if ($PSCmdlet.ShouldProcess($sched.Parent.Parent.Name, "Removing the schedule $($sched.Name) with id $($sched.Id) and uid $($sched.ScheduleUid) on $($sched.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $sched.Parent.Parent.ComputerName InstanceName = $sched.Parent.Parent.ServiceName SqlInstance = $sched.Parent.Parent.DomainInstanceName @@ -161,4 +161,4 @@ function Remove-DbaAgentSchedule { } } } -} +} \ No newline at end of file diff --git a/public/Remove-DbaAvailabilityGroup.ps1 b/public/Remove-DbaAvailabilityGroup.ps1 index ea95190459..cfb5d7075e 100644 --- a/public/Remove-DbaAvailabilityGroup.ps1 +++ b/public/Remove-DbaAvailabilityGroup.ps1 @@ -100,7 +100,7 @@ function Remove-DbaAvailabilityGroup { # avoid enumeration issues try { $ag.Parent.Query("DROP AVAILABILITY GROUP $ag") - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $ag.ComputerName InstanceName = $ag.InstanceName SqlInstance = $ag.SqlInstance diff --git a/public/Remove-DbaComputerCertificate.ps1 b/public/Remove-DbaComputerCertificate.ps1 index 2899e9a391..0ce7cf6198 100644 --- a/public/Remove-DbaComputerCertificate.ps1 +++ b/public/Remove-DbaComputerCertificate.ps1 @@ -144,7 +144,7 @@ function Remove-DbaComputerCertificate { $status = "Certificate not found in Cert:\$Store\$Folder" } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME Store = $Store Folder = $Folder diff --git a/public/Remove-DbaCredential.ps1 b/public/Remove-DbaCredential.ps1 index f9e1e8c271..a6da3bd32e 100644 --- a/public/Remove-DbaCredential.ps1 +++ b/public/Remove-DbaCredential.ps1 @@ -103,7 +103,7 @@ function Remove-DbaCredential { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaCredential. foreach ($dbCredential in $dbCredentials) { if ($PSCmdlet.ShouldProcess($dbCredential.Parent.Parent.Name, "Removing the SQL credential $($dbCredential.Name) on $($dbCredential.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $dbCredential.ComputerName InstanceName = $dbCredential.InstanceName SqlInstance = $dbCredential.SqlInstance diff --git a/public/Remove-DbaDatabase.ps1 b/public/Remove-DbaDatabase.ps1 index 788755be17..c9cc4b527d 100644 --- a/public/Remove-DbaDatabase.ps1 +++ b/public/Remove-DbaDatabase.ps1 @@ -105,7 +105,7 @@ function Remove-DbaDatabase { $server.Refresh() Remove-TeppCacheItem -SqlInstance $server -Type database -Name $db.name - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -118,7 +118,7 @@ function Remove-DbaDatabase { if ($Pscmdlet.ShouldProcess("$db on $server", "alter db set single_user with rollback immediate then drop")) { $null = $server.Query("if exists (select * from sys.databases where name = '$($db.name)' and state = 0) alter database $db set single_user with rollback immediate; drop database $db") - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -133,7 +133,7 @@ function Remove-DbaDatabase { $db.Parent.databases[$dbName].Drop() $server.Refresh() - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -144,7 +144,7 @@ function Remove-DbaDatabase { } catch { Write-Message -Level Verbose -Message "Could not drop database $db on $server" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Remove-DbaDbAsymmetricKey.ps1 b/public/Remove-DbaDbAsymmetricKey.ps1 index 6556273b2e..52cc0b4d8b 100644 --- a/public/Remove-DbaDbAsymmetricKey.ps1 +++ b/public/Remove-DbaDbAsymmetricKey.ps1 @@ -82,7 +82,7 @@ function Remove-DbaDbAsymmetricKey { # Avoids modifying the collection Invoke-DbaQuery -SqlInstance $server -Database $db.Name -Query "DROP ASYMMETRIC KEY $($askey.Name)" -EnableException Write-Message -Level Verbose -Message "Successfully removed asymmetric key named $Name from the $db database on $server" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Remove-DbaDbCertificate.ps1 b/public/Remove-DbaDbCertificate.ps1 index 0d6c4d7f43..4b41b4cd1a 100644 --- a/public/Remove-DbaDbCertificate.ps1 +++ b/public/Remove-DbaDbCertificate.ps1 @@ -82,7 +82,7 @@ function Remove-DbaDbCertificate { # Avoids modifying the collection Invoke-DbaQuery -SqlInstance $server -Database $db.Name -Query "DROP CERTIFICATE $cert" -EnableException Write-Message -Level Verbose -Message "Successfully removed certificate named $cert from the $db database on $server" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Remove-DbaDbCheckConstraint.ps1 b/public/Remove-DbaDbCheckConstraint.ps1 index 078123c849..e269a138a8 100644 --- a/public/Remove-DbaDbCheckConstraint.ps1 +++ b/public/Remove-DbaDbCheckConstraint.ps1 @@ -99,7 +99,7 @@ function Remove-DbaDbCheckConstraint { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaDbUdf. foreach ($chkcItem in $chkcs) { if ($PSCmdlet.ShouldProcess($chkcItem.Parent.Parent.Parent.Name, "Removing the check constraint [$($chkcItem.Name)] on the table $($chkcItem.Parent) on the database [$($chkcItem.Parent.Parent.Name)]")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $chkcItem.ComputerName InstanceName = $chkcItem.Parent.Parent.Parent.ServiceName SqlInstance = $chkcItem.Parent.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaDbEncryptionKey.ps1 b/public/Remove-DbaDbEncryptionKey.ps1 index 8ab894e5f1..5addc6655e 100644 --- a/public/Remove-DbaDbEncryptionKey.ps1 +++ b/public/Remove-DbaDbEncryptionKey.ps1 @@ -81,7 +81,7 @@ function Remove-DbaDbEncryptionKey { # Avoids modifying the collection Invoke-DbaQuery -SqlInstance $server -Database $db.Name -Query "DROP DATABASE ENCRYPTION KEY" -EnableException Write-Message -Level Verbose -Message "Successfully removed encryption key from the $db database on $server" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Remove-DbaDbMailAccount.ps1 b/public/Remove-DbaDbMailAccount.ps1 index 2119e19bb4..215afc9fad 100644 --- a/public/Remove-DbaDbMailAccount.ps1 +++ b/public/Remove-DbaDbMailAccount.ps1 @@ -98,7 +98,7 @@ function Remove-DbaDbMailAccount { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaDbMailAccount. foreach ($dbMailAccount in $dbMailAccounts) { if ($PSCmdlet.ShouldProcess($dbMailAccount.Parent.Parent.Name, "Removing the database mail account $($dbMailAccount.Name) on $($dbMailAccount.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $dbMailAccount.Parent.Parent.ComputerName InstanceName = $dbMailAccount.Parent.Parent.ServiceName SqlInstance = $dbMailAccount.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaDbMailProfile.ps1 b/public/Remove-DbaDbMailProfile.ps1 index aa99856bc2..d7b57ac1ae 100644 --- a/public/Remove-DbaDbMailProfile.ps1 +++ b/public/Remove-DbaDbMailProfile.ps1 @@ -101,7 +101,7 @@ function Remove-DbaDbMailProfile { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaDbMailProfile. foreach ($dbMailProfile in $dbMailProfiles) { if ($PSCmdlet.ShouldProcess($dbMailProfile.Parent.Parent.Name, "Removing the database mail profile $($dbMailProfile.Name) on $($dbMailProfile.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $dbMailProfile.Parent.Parent.ComputerName InstanceName = $dbMailProfile.Parent.Parent.ServiceName SqlInstance = $dbMailProfile.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaDbMasterKey.ps1 b/public/Remove-DbaDbMasterKey.ps1 index 0df7bee579..27acaa122f 100644 --- a/public/Remove-DbaDbMasterKey.ps1 +++ b/public/Remove-DbaDbMasterKey.ps1 @@ -100,7 +100,7 @@ function Remove-DbaDbMasterKey { # avoid enumeration issues try { $masterkey.Parent.Query("DROP MASTER KEY") - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Remove-DbaDbMirror.ps1 b/public/Remove-DbaDbMirror.ps1 index c3feab9d67..6cff6efe4b 100644 --- a/public/Remove-DbaDbMirror.ps1 +++ b/public/Remove-DbaDbMirror.ps1 @@ -97,7 +97,7 @@ function Remove-DbaDbMirror { } } } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $db.ComputerName InstanceName = $db.InstanceName SqlInstance = $db.SqlInstance diff --git a/public/Remove-DbaDbMirrorMonitor.ps1 b/public/Remove-DbaDbMirrorMonitor.ps1 index 47631c1634..c7c795a22a 100644 --- a/public/Remove-DbaDbMirrorMonitor.ps1 +++ b/public/Remove-DbaDbMirrorMonitor.ps1 @@ -62,7 +62,7 @@ function Remove-DbaDbMirrorMonitor { if ($Pscmdlet.ShouldProcess($instance, "Removing mirror monitoring")) { try { $server.Query("msdb.dbo.sp_dbmmonitordropmonitoring") - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Remove-DbaDbOrphanUser.ps1 b/public/Remove-DbaDbOrphanUser.ps1 index 863d99a8a8..706d9ba699 100644 --- a/public/Remove-DbaDbOrphanUser.ps1 +++ b/public/Remove-DbaDbOrphanUser.ps1 @@ -210,7 +210,7 @@ function Remove-DbaDbOrphanUser { if ($Pscmdlet.ShouldProcess($db.Name, "Changing schema '$($sch.Name)' owner to 'dbo'. -Force used.")) { $AlterSchemaOwner += "ALTER AUTHORIZATION ON SCHEMA::[$($sch.Name)] TO [dbo]$eol" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -233,7 +233,7 @@ function Remove-DbaDbOrphanUser { if ($Pscmdlet.ShouldProcess($db.Name, "Dropping schema '$($sch.Name)'.")) { $DropSchema += "DROP SCHEMA [$($sch.Name)]" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -250,7 +250,7 @@ function Remove-DbaDbOrphanUser { if ($Pscmdlet.ShouldProcess($db.Name, "Changing schema '$($sch.Name)' owner to 'dbo'.")) { $AlterSchemaOwner += "ALTER AUTHORIZATION ON SCHEMA::[$($sch.Name)] TO [dbo]$eol" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Remove-DbaDbPartitionFunction.ps1 b/public/Remove-DbaDbPartitionFunction.ps1 index 745f3d1967..031b58606c 100644 --- a/public/Remove-DbaDbPartitionFunction.ps1 +++ b/public/Remove-DbaDbPartitionFunction.ps1 @@ -90,7 +90,7 @@ function Remove-DbaDbPartitionFunction { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaDbPartitionFunction. foreach ($partfunItem in $partfuns) { if ($PSCmdlet.ShouldProcess($partfunItem.Parent.Parent.Name, "Removing the partition function [$($partfunItem.Name)] in the database [$($partfunItem.Parent.Name)] on [$($partfunItem.Parent.Parent.Name)]")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $partfunItem.Parent.Parent.ComputerName InstanceName = $partfunItem.Parent.Parent.ServiceName SqlInstance = $partfunItem.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaDbPartitionScheme.ps1 b/public/Remove-DbaDbPartitionScheme.ps1 index ed1245b936..c07f22ebad 100644 --- a/public/Remove-DbaDbPartitionScheme.ps1 +++ b/public/Remove-DbaDbPartitionScheme.ps1 @@ -90,7 +90,7 @@ function Remove-DbaDbPartitionScheme { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaDbPartitionScheme. foreach ($partschItem in $partschs) { if ($PSCmdlet.ShouldProcess($partschItem.Parent.Parent.Name, "Removing the partition scheme [$($partschItem.Name)] in the database [$($partschItem.Parent.Name)] on [$($partschItem.Parent.Parent.Name)]")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $partschItem.Parent.Parent.ComputerName InstanceName = $partschItem.Parent.Parent.ServiceName SqlInstance = $partschItem.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaDbRole.ps1 b/public/Remove-DbaDbRole.ps1 index 8a02d7b839..2b40b35124 100644 --- a/public/Remove-DbaDbRole.ps1 +++ b/public/Remove-DbaDbRole.ps1 @@ -108,15 +108,15 @@ function Remove-DbaDbRole { switch ($inputType) { 'Dataplat.Dbatools.Parameter.DbaInstanceParameter' { Write-Message -Level Verbose -Message "Processing DbaInstanceParameter through InputObject" - $dbRoles = Get-DbaDBRole -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase -Role $Role -ExcludeRole $ExcludeRole -ExcludeFixedRole:$True + $dbRoles = Get-DbaDbRole -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase -Role $Role -ExcludeRole $ExcludeRole -ExcludeFixedRole:$True } 'Microsoft.SqlServer.Management.Smo.Server' { Write-Message -Level Verbose -Message "Processing Server through InputObject" - $dbRoles = Get-DbaDBRole -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase -Role $Role -ExcludeRole $ExcludeRole -ExcludeFixedRole:$True + $dbRoles = Get-DbaDbRole -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase -Role $Role -ExcludeRole $ExcludeRole -ExcludeFixedRole:$True } 'Microsoft.SqlServer.Management.Smo.Database' { Write-Message -Level Verbose -Message "Processing Database through InputObject" - $dbRoles = $input | Get-DbaDBRole -ExcludeDatabase $ExcludeDatabase -Role $Role -ExcludeRole $ExcludeRole -ExcludeFixedRole:$True + $dbRoles = $input | Get-DbaDbRole -ExcludeDatabase $ExcludeDatabase -Role $Role -ExcludeRole $ExcludeRole -ExcludeFixedRole:$True } 'Microsoft.SqlServer.Management.Smo.DatabaseRole' { Write-Message -Level Verbose -Message "Processing DatabaseRole through InputObject" diff --git a/public/Remove-DbaDbRoleMember.ps1 b/public/Remove-DbaDbRoleMember.ps1 index c4b46f05af..38c56560b4 100644 --- a/public/Remove-DbaDbRoleMember.ps1 +++ b/public/Remove-DbaDbRoleMember.ps1 @@ -106,15 +106,15 @@ function Remove-DbaDbRoleMember { switch ($inputType) { 'Dataplat.Dbatools.Parameter.DbaInstanceParameter' { Write-Message -Level Verbose -Message "Processing DbaInstanceParameter through InputObject" - $dbRoles = Get-DbaDBRole -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -Role $Role + $dbRoles = Get-DbaDbRole -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -Role $Role } 'Microsoft.SqlServer.Management.Smo.Server' { Write-Message -Level Verbose -Message "Processing Server through InputObject" - $dbRoles = Get-DbaDBRole -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -Role $Role + $dbRoles = Get-DbaDbRole -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -Role $Role } 'Microsoft.SqlServer.Management.Smo.Database' { Write-Message -Level Verbose -Message "Processing Database through InputObject" - $dbRoles = $input | Get-DbaDBRole -Role $Role + $dbRoles = $input | Get-DbaDbRole -Role $Role } 'Microsoft.SqlServer.Management.Smo.DatabaseRole' { Write-Message -Level Verbose -Message "Processing DatabaseRole through InputObject" diff --git a/public/Remove-DbaDbSequence.ps1 b/public/Remove-DbaDbSequence.ps1 index d6e99e697c..395fd4c841 100644 --- a/public/Remove-DbaDbSequence.ps1 +++ b/public/Remove-DbaDbSequence.ps1 @@ -102,7 +102,7 @@ function Remove-DbaDbSequence { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaDbSequence. foreach ($sequenceItem in $sequences) { if ($PSCmdlet.ShouldProcess($sequenceItem.Parent.Parent.Name, "Removing the sequence $($sequenceItem.Schema).$($sequenceItem.Name) in the database $($sequenceItem.Parent.Name) on $($sequenceItem.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $sequenceItem.Parent.Parent.ComputerName InstanceName = $sequenceItem.Parent.Parent.ServiceName SqlInstance = $sequenceItem.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaDbSnapshot.ps1 b/public/Remove-DbaDbSnapshot.ps1 index 6c37a4b029..d161c543bc 100644 --- a/public/Remove-DbaDbSnapshot.ps1 +++ b/public/Remove-DbaDbSnapshot.ps1 @@ -147,7 +147,7 @@ function Remove-DbaDbSnapshot { $db.Drop() $server.Refresh() - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -158,7 +158,7 @@ function Remove-DbaDbSnapshot { } catch { Write-Message -Level Verbose -Message "Could not drop database $db on $server" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Remove-DbaDbSynonym.ps1 b/public/Remove-DbaDbSynonym.ps1 index 0bcb2f45b7..d981520284 100644 --- a/public/Remove-DbaDbSynonym.ps1 +++ b/public/Remove-DbaDbSynonym.ps1 @@ -112,15 +112,15 @@ function Remove-DbaDbSynonym { switch ($inputType) { 'Dataplat.Dbatools.Parameter.DbaInstanceParameter' { Write-Message -Level Verbose -Message "Processing DbaInstanceParameter through InputObject" - $dbSynonyms = Get-DbaDBSynonym -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase -Schema $Schema -ExcludeSchema $ExcludeSchema -Synonym $Synonym -ExcludeSynonym $ExcludeSynonym + $dbSynonyms = Get-DbaDbSynonym -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase -Schema $Schema -ExcludeSchema $ExcludeSchema -Synonym $Synonym -ExcludeSynonym $ExcludeSynonym } 'Microsoft.SqlServer.Management.Smo.Server' { Write-Message -Level Verbose -Message "Processing Server through InputObject" - $dbSynonyms = Get-DbaDBSynonym -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase -Schema $Schema -ExcludeSchema $ExcludeSchema -Synonym $Synonym -ExcludeSynonym $ExcludeSynonym + $dbSynonyms = Get-DbaDbSynonym -SqlInstance $input -SqlCredential $SqlCredential -Database $Database -ExcludeDatabase $ExcludeDatabase -Schema $Schema -ExcludeSchema $ExcludeSchema -Synonym $Synonym -ExcludeSynonym $ExcludeSynonym } 'Microsoft.SqlServer.Management.Smo.Database' { Write-Message -Level Verbose -Message "Processing Database through InputObject" - $dbSynonyms = Get-DBaDbSynonym -InputObject $input + $dbSynonyms = Get-DbaDbSynonym -InputObject $input } 'Microsoft.SqlServer.Management.Smo.Synonym' { Write-Message -Level Verbose -Message "Processing DatabaseSynonym through InputObject" @@ -141,7 +141,7 @@ function Remove-DbaDbSynonym { try { # avoid enumeration issues $db.Query("DROP SYNONYM $dbSynonym") - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $db.ComputerName InstanceName = $db.InstanceName SqlInstance = $db.SqlInstance diff --git a/public/Remove-DbaDbTable.ps1 b/public/Remove-DbaDbTable.ps1 index d20cc38bf2..ea6027362d 100644 --- a/public/Remove-DbaDbTable.ps1 +++ b/public/Remove-DbaDbTable.ps1 @@ -93,7 +93,7 @@ function Remove-DbaDbTable { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaDbTable. foreach ($tableItem in $tables) { if ($PSCmdlet.ShouldProcess($tableItem.Parent.Parent.Name, "Removing the table $($tableItem.Schema).$($tableItem.Name) in the database $($tableItem.Parent.Name) on $($tableItem.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $tableItem.Parent.Parent.ComputerName InstanceName = $tableItem.Parent.Parent.ServiceName SqlInstance = $tableItem.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaDbTableData.ps1 b/public/Remove-DbaDbTableData.ps1 index 431ff30112..5e5776095c 100644 --- a/public/Remove-DbaDbTableData.ps1 +++ b/public/Remove-DbaDbTableData.ps1 @@ -333,7 +333,7 @@ function Remove-DbaDbTableData { } while ($rowCount -gt 0) - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $db.Parent.ComputerName InstanceName = $db.Parent.Name Database = $db.Name diff --git a/public/Remove-DbaDbUdf.ps1 b/public/Remove-DbaDbUdf.ps1 index 0f09cb5dec..25f4f58a44 100644 --- a/public/Remove-DbaDbUdf.ps1 +++ b/public/Remove-DbaDbUdf.ps1 @@ -119,7 +119,7 @@ function Remove-DbaDbUdf { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaDbUdf. foreach ($udfItem in $udfs) { if ($PSCmdlet.ShouldProcess($udfItem.Parent.Parent.Name, "Removing the user defined function $($udfItem.Schema).$($udfItem.Name) in the database $($udfItem.Parent.Name) on $($udfItem.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $udfItem.Parent.Parent.ComputerName InstanceName = $udfItem.Parent.Parent.ServiceName SqlInstance = $udfItem.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaDbView.ps1 b/public/Remove-DbaDbView.ps1 index 92477ea814..8f130847d3 100644 --- a/public/Remove-DbaDbView.ps1 +++ b/public/Remove-DbaDbView.ps1 @@ -94,7 +94,7 @@ function Remove-DbaDbView { # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaDbView. foreach ($viewItem in $views) { if ($PSCmdlet.ShouldProcess($viewItem.Parent.Parent.Name, "Removing the view $($viewItem.Schema).$($viewItem.Name) in the database $($viewItem.Parent.Name) on $($viewItem.Parent.Parent.Name)")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $viewItem.Parent.Parent.ComputerName InstanceName = $viewItem.Parent.Parent.ServiceName SqlInstance = $viewItem.Parent.Parent.DomainInstanceName diff --git a/public/Remove-DbaEndpoint.ps1 b/public/Remove-DbaEndpoint.ps1 index 504d2099b4..f7e281e6bd 100644 --- a/public/Remove-DbaEndpoint.ps1 +++ b/public/Remove-DbaEndpoint.ps1 @@ -86,7 +86,7 @@ function Remove-DbaEndpoint { try { # avoid enumeration issues $ep.Parent.Query("DROP ENDPOINT $ep") - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $ep.ComputerName InstanceName = $ep.InstanceName SqlInstance = $ep.SqlInstance diff --git a/public/Remove-DbaExtendedProperty.ps1 b/public/Remove-DbaExtendedProperty.ps1 index fa82dfa73c..cd845a725e 100644 --- a/public/Remove-DbaExtendedProperty.ps1 +++ b/public/Remove-DbaExtendedProperty.ps1 @@ -54,7 +54,7 @@ function Remove-DbaExtendedProperty { $db = $object | Get-ConnectionParent -Database try { $null = $db.Invoke("EXEC sp_dropextendedproperty @name = N'$($object.Name)'; ") - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $object.ComputerName InstanceName = $object.InstanceName SqlInstance = $object.SqlInstance diff --git a/public/Remove-DbaLogin.ps1 b/public/Remove-DbaLogin.ps1 index 02232a14e6..094c16064d 100644 --- a/public/Remove-DbaLogin.ps1 +++ b/public/Remove-DbaLogin.ps1 @@ -102,7 +102,7 @@ function Remove-DbaLogin { Remove-TeppCacheItem -SqlInstance $server -Type login -Name $currentlogin.name - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -111,7 +111,7 @@ function Remove-DbaLogin { } } } catch { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Remove-DbaNetworkCertificate.ps1 b/public/Remove-DbaNetworkCertificate.ps1 index 9f0f63e846..1277f4b06b 100644 --- a/public/Remove-DbaNetworkCertificate.ps1 +++ b/public/Remove-DbaNetworkCertificate.ps1 @@ -118,7 +118,7 @@ function Remove-DbaNetworkCertificate { $thumbprint = (Get-ItemProperty -Path $regPath -Name Certificate).Certificate Set-ItemProperty -Path $regPath -Name Certificate -Value $null - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME InstanceName = $instanceName SqlInstance = $vsname diff --git a/public/Remove-DbaPfDataCollectorCounter.ps1 b/public/Remove-DbaPfDataCollectorCounter.ps1 index aa8d6abac8..d6e03c284b 100644 --- a/public/Remove-DbaPfDataCollectorCounter.ps1 +++ b/public/Remove-DbaPfDataCollectorCounter.ps1 @@ -124,7 +124,7 @@ function Remove-DbaPfDataCollectorCounter { try { $results = Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $setscript -ArgumentList $setname, $plainxml -ErrorAction Stop -Raw Write-Message -Level Verbose -Message " $results" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $computer DataCollectorSet = $setname DataCollector = $collectorname diff --git a/public/Remove-DbaPfDataCollectorSet.ps1 b/public/Remove-DbaPfDataCollectorSet.ps1 index a8f1443610..cbd0205b7a 100644 --- a/public/Remove-DbaPfDataCollectorSet.ps1 +++ b/public/Remove-DbaPfDataCollectorSet.ps1 @@ -124,7 +124,7 @@ function Remove-DbaPfDataCollectorSet { if ($Pscmdlet.ShouldProcess("$computer", "Removing collector set $setname")) { try { Invoke-Command2 -ComputerName $computer -Credential $Credential -ScriptBlock $setscript -ArgumentList $setname -ErrorAction Stop - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $computer Name = $setname Status = "Removed" diff --git a/public/Remove-DbaRegServer.ps1 b/public/Remove-DbaRegServer.ps1 index 65da91d408..d9fe74f8e6 100644 --- a/public/Remove-DbaRegServer.ps1 +++ b/public/Remove-DbaRegServer.ps1 @@ -111,7 +111,7 @@ function Remove-DbaRegServer { } try { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $regserver.ComputerName InstanceName = $regserver.InstanceName SqlInstance = $regserver.SqlInstance diff --git a/public/Remove-DbaRegServerGroup.ps1 b/public/Remove-DbaRegServerGroup.ps1 index 12d7c70b9c..219ec1b7e9 100644 --- a/public/Remove-DbaRegServerGroup.ps1 +++ b/public/Remove-DbaRegServerGroup.ps1 @@ -103,7 +103,7 @@ function Remove-DbaRegServerGroup { } try { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $parentserver.ComputerName InstanceName = $parentserver.InstanceName SqlInstance = $parentserver.SqlInstance diff --git a/public/Remove-DbaReplArticle.ps1 b/public/Remove-DbaReplArticle.ps1 new file mode 100644 index 0000000000..a4354240a4 --- /dev/null +++ b/public/Remove-DbaReplArticle.ps1 @@ -0,0 +1,152 @@ +function Remove-DbaReplArticle { + <# + .SYNOPSIS + Removes an article from a publication for the database on the target SQL instances. + + .DESCRIPTION + Removes an article from a publication for the database on the target SQL instances. + + Dropping an article from a publication does not remove the object from the publication database or the corresponding object from the subscription database. + Use DROP to remove these objects if necessary. + #TODO: add a param for this DropObjectOnSubscriber + + Dropping an article invalidates the current snapshot; therefore a new snapshot must be created. + + .PARAMETER SqlInstance + The target SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER Database + The database on the publisher that contains the article to be removed from replication. + + .PARAMETER Publication + The name of the replication publication. + + .PARAMETER Schema + Source schema of the replicated object to remove from the publication. + + .PARAMETER Name + The name of the article to remove. + + .PARAMETER DropObjectOnSubscriber + If this switch is enabled, the object will be dropped from the subscriber database. + + .PARAMETER InputObject + Enables piping from Get-DbaReplArticle + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .PARAMETER WhatIf + If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. + + .PARAMETER Confirm + If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. + + .NOTES + Tags: repl, Replication + Author: Jess Pomfret (@jpomfret), jesspomfret.com + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + https://learn.microsoft.com/en-us/sql/relational-databases/replication/publish/delete-an-article + + .LINK + https://dbatools.io/Remove-DbaReplArticle + + .EXAMPLE + PS C:\> Remove-DbaReplArticle -SqlInstance mssql1 -Database Pubs -Publication PubFromPosh -Name 'publishers' + + Removes the publishers article from a publication called PubFromPosh on mssql1 + + .EXAMPLE + + PS C:\> Get-DbaReplArticle -SqlInstance mssql1 -Database Pubs -Publication TestPub | Remove-DbaReplArticle + + Removes all articles from a publication called TestPub on mssql1 + #> + [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess, ConfirmImpact = 'High')] + param ( + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [String]$Database, + [String]$Publication, + [String]$Schema = 'dbo', + [String]$Name, + #[Switch]$DropObjectOnSubscriber, + [Parameter(ValueFromPipeline)] + [Microsoft.SqlServer.Replication.Article[]]$InputObject, + [Switch]$EnableException + ) + + begin { + $articles = @( ) + } + + process { + if (-not $PSBoundParameters.SqlInstance -and -not $PSBoundParameters.InputObject) { + Stop-Function -Message "You must specify either SqlInstance or InputObject" + return + } + + if ($InputObject) { + $articles += $InputObject + } else { + $params = $PSBoundParameters + $null = $params.Remove('InputObject') + $null = $params.Remove('WhatIf') + $null = $params.Remove('Confirm') + $articles = Get-DbaReplArticle @params + } + } + + end { + # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaReplArticle. + foreach ($art in $articles) { + if ($PSCmdlet.ShouldProcess($art.Name, "Removing the article $($art.SourceObjectOwner).$($art.SourceObjectName) from the $($art.PublicationName) publication on $($art.SqlInstance)")) { + $output = [pscustomobject]@{ + ComputerName = $art.ComputerName + InstanceName = $art.InstanceName + SqlInstance = $art.SqlInstance + Database = $art.DatabaseName + ObjectName = $art.SourceObjectName + ObjectSchema = $art.SourceObjectOwner + Status = $null + IsRemoved = $false + } + try { + + $pub = Get-DbaReplPublication -SqlInstance $art.SqlInstance -SqlCredential $SqlCredential -Database $art.DatabaseName -Name $art.PublicationName -EnableException:$EnableException + + if (($pub.Subscriptions | Measure-Object).count -gt 0 ) { + Write-Message -Level Verbose -Message ("There is a subscription so remove article {0} from subscription on {1}" -f $art.Name, $pub.Subscriptions.SubscriberName) + $query = "exec sp_dropsubscription @publication = '{0}', @article= '{1}',@subscriber = '{2}'" -f $art.PublicationName, $art.Name, $pub.Subscriptions.SubscriberName + Invoke-DbaQuery -SqlInstance $art.SqlInstance -SqlCredential $SqlCredential -Database $art.DatabaseName -query $query -EnableException:$EnableException + } + if (($art.IsExistingObject)) { + $art.Remove() + } else { + Stop-Function -Message "Article doesn't exist in $PublicationName on $instance" -ErrorRecord $_ -Target $instance -Continue + } + $output.Status = "Removed" + $output.IsRemoved = $true + } catch { + Stop-Function -Message "Failed to remove the article from publication" -ErrorRecord $_ + $output.Status = (Get-ErrorMessage -Record $_) + $output.IsRemoved = $false + } + $output + } + } + } +} \ No newline at end of file diff --git a/public/Remove-DbaReplPublication.ps1 b/public/Remove-DbaReplPublication.ps1 new file mode 100644 index 0000000000..4959879e67 --- /dev/null +++ b/public/Remove-DbaReplPublication.ps1 @@ -0,0 +1,186 @@ +function Remove-DbaReplPublication { + <# + .SYNOPSIS + Removes a publication from the database on the target SQL instances. + + .DESCRIPTION + Removes a publication from the database on the target SQL instances. + + https://learn.microsoft.com/en-us/sql/relational-databases/replication/publish/delete-a-publication?view=sql-server-ver16#RMOProcedure + + .PARAMETER SqlInstance + The target SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER Database + The database that will be replicated. + + .PARAMETER Name + The name of the replication publication + + .PARAMETER InputObject + A publication object retrieved from Get-DbaReplPublication. Enables piping from Get-DbaReplPublication. + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .PARAMETER WhatIf + If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. + + .PARAMETER Confirm + If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. + + .NOTES + Tags: repl, Replication + Author: Jess Pomfret (@jpomfret), jesspomfret.com + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/Remove-DbaReplPublication + + .EXAMPLE + PS C:\> Remove-DbaReplPublication -SqlInstance mssql1 -Database Northwind -Name PubFromPosh + + Removes a publication called PubFromPosh from the Northwind database on mssql1 + + #> + [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess, ConfirmImpact = 'High')] + param ( + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [String]$Database, + [String]$Name, + [parameter(ValueFromPipeline)] + [Microsoft.SqlServer.Replication.Publication[]]$InputObject, + [Switch]$EnableException + ) + begin { + $publications = @( ) + } + process { + if (-not $PSBoundParameters.SqlInstance -and -not $PSBoundParameters.InputObject) { + Stop-Function -Message "You must specify either SqlInstance or InputObject" + return + } + + if ($InputObject) { + $publications += $InputObject + } else { + $params = $PSBoundParameters + $null = $params.Remove('InputObject') + $null = $params.Remove('WhatIf') + $null = $params.Remove('Confirm') + $publications = Get-DbaReplPublication @params + } + } + + end { + # We have to delete in the end block to prevent "Collection was modified; enumeration operation may not execute." if directly piped from Get-DbaReplArticle. + foreach ($pub in $publications) { + if ($PSCmdlet.ShouldProcess($pub.Name, "Removing the publication $($pub.Name) on $($pub.SqlInstance)")) { + $output = [PSCustomObject]@{ + ComputerName = $pub.ComputerName + InstanceName = $pub.InstanceName + SqlInstance = $pub.SqlInstance + Database = $pub.DatabaseName + Name = $pub.Name + Type = $pub.Type + Status = $null + IsRemoved = $false + } + + if ($pub.Type -in ('Transactional', 'Snapshot')) { + try { + if ($pub.IsExistingObject) { + Write-Message -Level Verbose -Message "Removing $($pub.Name) from $($pub.SqlInstance).$($pub.DatabaseName)" + + if ($PSCmdlet.ShouldProcess($pub.Name, "Stopping the REPL-LogReader job for the database $($pub.DatabaseName) on $($pub.SqlInstance)")) { + $null = Get-DbaAgentJob -SqlInstance $pub.SqlInstance -SqlCredential $SqlCredential -Category REPL-LogReader | Where-Object { $_.Name -like ('*{0}*' -f $pub.DatabaseName) } | Stop-DbaAgentJob + } + $pub.Remove() + + $output.Status = "Removed" + $output.IsRemoved = $true + } + } catch { + Stop-Function -Message "Failed to remove the publication from $($pub.SqlInstance)" -ErrorRecord $_ + $output.Status = (Get-ErrorMessage -Record $_) + $output.IsRemoved = $false + } + + try { + # If no other transactional publications exist for this database, the database can be disabled for transactional publishing + if (-not (Get-DbaReplPublication -SqlInstance $pub.SqlInstance -SqlCredential $SqlCredential -Database $pub.DatabaseName -Type Transactional, Snapshot -EnableException:$EnableException)) { + $pubDatabase = New-Object Microsoft.SqlServer.Replication.ReplicationDatabase + $pubDatabase.ConnectionContext = $pub.ConnectionContext + $pubDatabase.Name = $pub.DatabaseName + if (-not $pubDatabase.LoadProperties()) { + throw "Database $Database not found on $($pub.SqlInstance)" + } + + if ($pubDatabase.EnabledTransPublishing) { + Write-Message -Level Verbose -Message "No transactional publications on $Instance.$Database so disabling transactional publishing" + $pubDatabase.EnabledTransPublishing = $false + } + } + } catch { + Stop-Function -Message "Failed to disable transactional publishing on $($pub.SqlInstance)" -ErrorRecord $_ + } + + } elseif ($pub.Type -eq 'Merge') { + try { + if ($pub.IsExistingObject) { + Write-Message -Level Verbose -Message "Removing $($pub.Name) from $($pub.SqlInstance).$($pub.DatabaseName)" + if ($PSCmdlet.ShouldProcess($pub.Name, "Stopping the REPL-LogReader job for the database $($pub.DatabaseName) on $($pub.SqlInstance)")) { + $null = Get-DbaAgentJob -SqlInstance $pub.SqlInstance -SqlCredential $SqlCredential -Category REPL-LogReader | Where-Object { $_.Name -like ('*{0}*' -f $pub.DatabaseName) } | Stop-DbaAgentJob + } + $pub.Remove() + + $output.Status = "Removed" + $output.IsRemoved = $true + } else { + Write-Warning "Didn't find $($pub.Name) on $($pub.SqlInstance).$($pub.DatabaseName)" + } + } catch { + Stop-Function -Message "Failed to remove the publication from $($pub.SqlInstance)" -ErrorRecord $_ + $output.Status = (Get-ErrorMessage -Record $_) + $output.IsRemoved = $false + } + + try { + # If no other merge publications exist for this database, the database can be disabled for merge publishing + if (-not (Get-DbaReplPublication -SqlInstance $pub.SqlInstance -SqlCredential $SqlCredential -Database $pub.DatabaseName -Type Merge -EnableException:$EnableException)) { + $pubDatabase = New-Object Microsoft.SqlServer.Replication.ReplicationDatabase + $pubDatabase.ConnectionContext = $pub.ConnectionContext + $pubDatabase.Name = $pub.DatabaseName + + if (-not $pubDatabase.LoadProperties()) { + throw "Database $Database not found on $instance" + } + + if ($pubDatabase.EnabledTransPublishing) { + Write-Message -Level Verbose -Message "No merge publications on $Instance.$Database so disabling merge publishing" + $pubDatabase.EnabledMergePublishing = $false + } + } + } catch { + Stop-Function -Message "Failed to disable transactional publishing on $($pub.SqlInstance)" -ErrorRecord $_ + } + } + + $output + } + } + } +} \ No newline at end of file diff --git a/public/Remove-DbaReplSubscription.ps1 b/public/Remove-DbaReplSubscription.ps1 new file mode 100644 index 0000000000..b9cd288961 --- /dev/null +++ b/public/Remove-DbaReplSubscription.ps1 @@ -0,0 +1,144 @@ +function Remove-DbaReplSubscription { + <# + .SYNOPSIS + Removes a subscription \for the target SQL instances. + + .DESCRIPTION + Removes a subscription for the target SQL instances. + + https://learn.microsoft.com/en-us/sql/relational-databases/replication/delete-a-push-subscription?view=sql-server-ver16 + https://learn.microsoft.com/en-us/sql/relational-databases/replication/delete-a-pull-subscription?view=sql-server-ver16 + + .PARAMETER SqlInstance + The target publisher SQL Server instance or instances. + + .PARAMETER SqlCredential + Login to the target publisher instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER Database + The database where the publication is located. + + .PARAMETER SubscriberSqlInstance + The subscriber SQL Server instance. + + .PARAMETER SubscriberSqlCredential + Login to the subscriber instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). + + Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported. + + For MFA support, please use Connect-DbaInstance. + + .PARAMETER PublicationName + The name of the publication. + + .PARAMETER SubscriptionDatabase + The database where the subscription is located. + + .PARAMETER EnableException + By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. + + .PARAMETER WhatIf + If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. + + .PARAMETER Confirm + If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. + + .NOTES + Tags: repl, Replication + Author: Jess Pomfret (@jpomfret), jesspomfret.com + + Website: https://dbatools.io + Copyright: (c) 2023 by dbatools, licensed under MIT + License: MIT https://opensource.org/licenses/MIT + + .LINK + https://dbatools.io/Remove-DbaReplSubscription + + .EXAMPLE + PS C:\> $sub = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'testPub' + SubscriberSqlInstance = 'mssql2' + SubscriptionDatabase = 'pubs' + } + PS C:\> Remove-DbaReplSubscription @sub + + Removes a subscription for the testPub publication on mssql2.pubs. + + #> + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')] + param ( + [Parameter(Mandatory, ValueFromPipeline)] + [DbaInstanceParameter[]]$SqlInstance, + [PSCredential]$SqlCredential, + [Parameter(Mandatory)] + [String]$Database, + [Parameter(Mandatory)] + [String]$PublicationName, + [Parameter(Mandatory)] + [DbaInstanceParameter]$SubscriberSqlInstance, + [PSCredential]$SubscriberSqlCredential, + [Parameter(Mandatory)] + [String]$SubscriptionDatabase, + [Switch]$EnableException + ) + begin { + + $pub = Get-DbaReplPublication -SqlInstance $SqlInstance -SqlCredential $SqlCredential -Name $PublicationName -EnableException:$EnableException + + if (-not $pub) { + Write-Warning "Didn't find a subscription to the $PublicationName publication on $SqlInstance.$Database" + } + + } + process { + foreach ($instance in $SubscriberSqlInstance) { + + try { + if ($PSCmdlet.ShouldProcess($instance, "Removing subscription to $PublicationName from $SqlInstance.$SubscriptionDatabase")) { + + if ($pub.Type -in ('Transactional', 'Snapshot')) { + + #TODO: Only handles push subscriptions at the moment - need to add pull subscriptions + # https://learn.microsoft.com/en-us/sql/relational-databases/replication/delete-a-pull-subscription?view=sql-server-ver16 + $transSub = New-Object Microsoft.SqlServer.Replication.TransSubscription + $transSub.ConnectionContext = $pub.ConnectionContext + $transSub.DatabaseName = $Database + $transSub.PublicationName = $PublicationName + $transSub.SubscriptionDBName = $SubscriptionDatabase + $transSub.SubscriberName = $instance + + if ($transSub.IsExistingObject) { + Write-Message -Level Verbose -Message "Removing the subscription" + $transSub.Remove() + } + + } elseif ($pub.Type -eq 'Merge') { + $mergeSub = New-Object Microsoft.SqlServer.Replication.MergeSubscription + $mergeSub.ConnectionContext = $pub.ConnectionContext + $mergeSub.DatabaseName = $Database + $mergeSub.PublicationName = $PublicationName + $mergeSub.SubscriptionDBName = $SubscriptionDatabase + $mergeSub.SubscriberName = $instance + + if ($mergeSub.IsExistingObject) { + Write-Message -Level Verbose -Message "Removing the merge subscription" + $mergeSub.Remove() + } else { + Write-Warning "Didn't find a subscription to $PublicationName on $($instance).$SubscriptionDatabase" + } + } + } + } catch { + Stop-Function -Message ("Unable to remove subscription - {0}" -f $_) -ErrorRecord $_ -Target $instance -Continue + } + } + } +} \ No newline at end of file diff --git a/public/Remove-DbaRgWorkloadGroup.ps1 b/public/Remove-DbaRgWorkloadGroup.ps1 index ee85f036d1..34f3b4cda9 100644 --- a/public/Remove-DbaRgWorkloadGroup.ps1 +++ b/public/Remove-DbaRgWorkloadGroup.ps1 @@ -107,7 +107,7 @@ function Remove-DbaRgWorkloadGroup { foreach ($wklGroup in $InputObject) { $server = $wklGroup.Parent.Parent.Parent if ($Pscmdlet.ShouldProcess($wklGroup, "Dropping workload group")) { - $output = [pscustomobject]@{ + $output = [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Remove-DbaServerRole.ps1 b/public/Remove-DbaServerRole.ps1 index 37dc3ef247..6e3c94262b 100644 --- a/public/Remove-DbaServerRole.ps1 +++ b/public/Remove-DbaServerRole.ps1 @@ -73,7 +73,7 @@ function Remove-DbaServerRole { try { $srvrole.Drop() - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $srvrole.ComputerName InstanceName = $srvrole.InstanceName SqlInstance = $srvrole.SqlInstance @@ -83,7 +83,7 @@ function Remove-DbaServerRole { } catch { Stop-Function -Message "Failed to drop server-role named $($srvrole.Name) on $($srvrole.Name)." -Target $srvrole -ErrorRecord $_ -Continue - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $srvrole.ComputerName InstanceName = $srvrole.InstanceName SqlInstance = $srvrole.SqlInstance diff --git a/public/Remove-DbaSpn.ps1 b/public/Remove-DbaSpn.ps1 index 682cd5f56b..1b7f43077b 100644 --- a/public/Remove-DbaSpn.ps1 +++ b/public/Remove-DbaSpn.ps1 @@ -125,7 +125,7 @@ function Remove-DbaSpn { $delegate = $false } - [pscustomobject]@{ + [PSCustomObject]@{ Name = $spn ServiceAccount = $ServiceAccount Property = "servicePrincipalName" @@ -139,7 +139,7 @@ function Remove-DbaSpn { if ($delegate) { # even if we removed the SPN, delegation could have been not set at all. We should not raise an error if ($adentry.Properties['msDS-AllowedToDelegateTo'] -notcontains $spn) { - [pscustomobject]@{ + [PSCustomObject]@{ Name = $spn ServiceAccount = $ServiceAccount Property = "msDS-AllowedToDelegateTo" @@ -160,7 +160,7 @@ function Remove-DbaSpn { $status = "Failed to remove delegation" } - [pscustomobject]@{ + [PSCustomObject]@{ Name = $spn ServiceAccount = $ServiceAccount Property = "msDS-AllowedToDelegateTo" diff --git a/public/Remove-DbaTrace.ps1 b/public/Remove-DbaTrace.ps1 index db81985fc0..c3720a94fc 100644 --- a/public/Remove-DbaTrace.ps1 +++ b/public/Remove-DbaTrace.ps1 @@ -97,7 +97,7 @@ function Remove-DbaTrace { if (Get-DbaTrace -SqlInstance $server -Id $traceid) { $server.Query($removesql) } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Remove-DbaXESession.ps1 b/public/Remove-DbaXESession.ps1 index 6148fd3699..81cb71bd36 100644 --- a/public/Remove-DbaXESession.ps1 +++ b/public/Remove-DbaXESession.ps1 @@ -101,7 +101,7 @@ function Remove-DbaXESession { if ($Pscmdlet.ShouldProcess("$instance", "Removing XEvent Session $session")) { try { $xe.Drop() - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $xe.Parent.ComputerName InstanceName = $xe.Parent.ServiceName SqlInstance = $xe.Parent.DomainInstanceName diff --git a/public/Rename-DbaDatabase.ps1 b/public/Rename-DbaDatabase.ps1 index ac4ca0fa87..2c632341d0 100644 --- a/public/Rename-DbaDatabase.ps1 +++ b/public/Rename-DbaDatabase.ps1 @@ -627,7 +627,7 @@ function Rename-DbaDatabase { $InstanceFiles[$Server_Id][$FNNameDir].Remove($FNName) $InstanceFiles[$Server_Id][$FNNameDir][$FinalFNName] = 1 $Entities_Before['FNN'][$FNName] = $FinalFNName - $Pending_Renames += [pscustomobject]@{ + $Pending_Renames += [PSCustomObject]@{ Source = $FNName Destination = $FinalFNName } @@ -677,7 +677,7 @@ function Rename-DbaDatabase { $InstanceFiles[$Server_Id][$FNNameDir].Remove($FNName) $InstanceFiles[$Server_Id][$FNNameDir][$FinalFNName] = 1 $Entities_Before['FNN'][$FNName] = $FinalFNName - $Pending_Renames += [pscustomobject]@{ + $Pending_Renames += [PSCustomObject]@{ Source = $FNName Destination = $FinalFNName } @@ -725,7 +725,7 @@ function Rename-DbaDatabase { } foreach ($op in $pending_renames) { if ([DbaValidate]::IsLocalhost($server.ComputerName)) { - $null = $Final_Renames.Add([pscustomobject]@{ + $null = $Final_Renames.Add([PSCustomObject]@{ Source = $op.Source Destination = $op.Destination ComputerName = $ComputerName @@ -734,14 +734,14 @@ function Rename-DbaDatabase { if ($null -eq $ComputerName) { # if we don't have remote access ($ComputerName is null) we can fallback to admin shares if they're available if (Test-Path (Join-AdminUnc -ServerName $server.ComputerName -filepath $op.Source)) { - $null = $Final_Renames.Add([pscustomobject]@{ + $null = $Final_Renames.Add([PSCustomObject]@{ Source = Join-AdminUnc -ServerName $server.ComputerName -filepath $op.Source Destination = Join-AdminUnc -ServerName $server.ComputerName -filepath $op.Destination ComputerName = $server.ComputerName }) } else { # flag the impossible rename ($ComputerName is $null) - $null = $Final_Renames.Add([pscustomobject]@{ + $null = $Final_Renames.Add([PSCustomObject]@{ Source = $op.Source Destination = $op.Destination ComputerName = $ComputerName @@ -749,7 +749,7 @@ function Rename-DbaDatabase { } } else { # we can do renames in a remote pssession - $null = $Final_Renames.Add([pscustomobject]@{ + $null = $Final_Renames.Add([PSCustomObject]@{ Source = $op.Source Destination = $op.Destination ComputerName = $ComputerName @@ -830,7 +830,7 @@ function Rename-DbaDatabase { $Entities_Before[$k].Remove($el) } } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Rename-DbaLogin.ps1 b/public/Rename-DbaLogin.ps1 index 030e5f0f00..9f4ce5b6d1 100644 --- a/public/Rename-DbaLogin.ps1 +++ b/public/Rename-DbaLogin.ps1 @@ -103,7 +103,7 @@ function Rename-DbaLogin { try { $dbMappings = $currentLogin.EnumDatabaseMappings() $null = $currentLogin.Rename($NewLogin) - $output += [pscustomobject]@{ + $output += [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -116,7 +116,7 @@ function Rename-DbaLogin { } } catch { $dbMappings = $null - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -142,7 +142,7 @@ function Rename-DbaLogin { try { $oldname = $user.name $null = $user.Rename($NewLogin) - $output += [pscustomobject]@{ + $output += [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -157,7 +157,7 @@ function Rename-DbaLogin { Write-Message -Level Warning -Message "Rolling back update to login: $Login" $null = $currentLogin.Rename($Login) - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Resolve-DbaNetworkName.ps1 b/public/Resolve-DbaNetworkName.ps1 index 975a62a539..1ab742b4c8 100644 --- a/public/Resolve-DbaNetworkName.ps1 +++ b/public/Resolve-DbaNetworkName.ps1 @@ -117,7 +117,7 @@ function Resolve-DbaNetworkName { process { if ((Get-DbatoolsConfigValue -FullName commands.resolve-dbanetworkname.bypass)) { foreach ($computer in $ComputerName) { - [pscustomobject]@{ + [PSCustomObject]@{ InputName = $computer ComputerName = $computer IPAddress = $computer diff --git a/public/Resolve-DbaPath.ps1 b/public/Resolve-DbaPath.ps1 index bff72823c7..bd2c2d0fb6 100644 --- a/public/Resolve-DbaPath.ps1 +++ b/public/Resolve-DbaPath.ps1 @@ -48,7 +48,7 @@ function Resolve-DbaPath { PS C:\> Resolve-DbaPath -Path ..\* This will resolve all items in the parent folder, whatever the current path or drive might be. -#> + #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true)] @@ -106,4 +106,4 @@ function Resolve-DbaPath { } } } -} +} \ No newline at end of file diff --git a/public/Restore-DbaDatabase.ps1 b/public/Restore-DbaDatabase.ps1 index 0729e9c9f3..6d921de165 100644 --- a/public/Restore-DbaDatabase.ps1 +++ b/public/Restore-DbaDatabase.ps1 @@ -833,4 +833,4 @@ function Restore-DbaDatabase { } } } -} +} \ No newline at end of file diff --git a/public/Revoke-DbaAgPermission.ps1 b/public/Revoke-DbaAgPermission.ps1 index e0d88528f2..0097227ce4 100644 --- a/public/Revoke-DbaAgPermission.ps1 +++ b/public/Revoke-DbaAgPermission.ps1 @@ -167,7 +167,7 @@ function Revoke-DbaAgPermission { try { $bigperms = New-Object Microsoft.SqlServer.Management.Smo.ObjectPermissionSet([Microsoft.SqlServer.Management.Smo.ObjectPermission]::$perm) $endpoint.Revoke($bigperms, $account.Name) - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $account.ComputerName InstanceName = $account.InstanceName SqlInstance = $account.SqlInstance @@ -194,7 +194,7 @@ function Revoke-DbaAgPermission { try { $bigperms = New-Object Microsoft.SqlServer.Management.Smo.ObjectPermissionSet([Microsoft.SqlServer.Management.Smo.ObjectPermission]::$perm) $ag.Revoke($bigperms, $account.Name) - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $account.ComputerName InstanceName = $account.InstanceName SqlInstance = $account.SqlInstance diff --git a/public/Save-DbaDiagnosticQueryScript.ps1 b/public/Save-DbaDiagnosticQueryScript.ps1 index 2360a53b7a..8b8c0fe679 100644 --- a/public/Save-DbaDiagnosticQueryScript.ps1 +++ b/public/Save-DbaDiagnosticQueryScript.ps1 @@ -75,7 +75,7 @@ function Save-DbaDiagnosticQueryScript { $page = Get-WebData -uri $glennberryResources $glenberrysql += ($page.Links | Where-Object { $_.href -like $DropboxLinkFilter -and $_.outerHTML -like $LinkTitleFilter -and $_.outerHTML -notlike $ExcludeSpreadsheet -and $_.outerHTML -like $FileTypeFilter } | ForEach-Object { - [pscustomobject]@{ + [PSCustomObject]@{ URL = $_.href SQLVersion = $_.outerHTML -replace "<.+`">", "" -replace "", "" -replace " Diagnostic Information Queries", "" -replace "SQL Server ", "" -replace ' ', '' } diff --git a/public/Select-DbaBackupInformation.ps1 b/public/Select-DbaBackupInformation.ps1 index 90ade43dff..887b8b84d8 100644 --- a/public/Select-DbaBackupInformation.ps1 +++ b/public/Select-DbaBackupInformation.ps1 @@ -181,7 +181,7 @@ function Select-DbaBackupInformation { } elseif ($true -eq $IgnoreFull -and $false -eq $IgnoreDiffs) { #Fake the Full backup Write-Message -Message "Continuing, so setting a fake full backup from the existing database" - $Full = [PsCustomObject]@{ + $Full = [PSCustomObject]@{ CheckpointLSN = ($ContinuePoints | Where-Object { $_.Database -eq $DatabaseFilter }).differential_base_lsn } } diff --git a/public/Set-DbaAgReplica.ps1 b/public/Set-DbaAgReplica.ps1 index 128854775d..c89675bcc7 100644 --- a/public/Set-DbaAgReplica.ps1 +++ b/public/Set-DbaAgReplica.ps1 @@ -224,4 +224,4 @@ function Set-DbaAgReplica { } } } -} +} \ No newline at end of file diff --git a/public/Set-DbaAgentJobOutputFile.ps1 b/public/Set-DbaAgentJobOutputFile.ps1 index d0a0e876e7..5540fc1962 100644 --- a/public/Set-DbaAgentJobOutputFile.ps1 +++ b/public/Set-DbaAgentJobOutputFile.ps1 @@ -133,7 +133,7 @@ function Set-DbaAgentJobOutputFile { $jobStep.Alter() $jobStep.Refresh() - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Set-DbaAgentJobStep.ps1 b/public/Set-DbaAgentJobStep.ps1 index ac922f1dd8..00e7141f4c 100644 --- a/public/Set-DbaAgentJobStep.ps1 +++ b/public/Set-DbaAgentJobStep.ps1 @@ -398,4 +398,4 @@ function Set-DbaAgentJobStep { if (Test-FunctionInterrupt) { return } Write-Message -Message "Finished changing job step(s)" -Level Verbose } -} +} \ No newline at end of file diff --git a/public/Set-DbaDbCompression.ps1 b/public/Set-DbaDbCompression.ps1 index 4011433cea..62ff268869 100644 --- a/public/Set-DbaDbCompression.ps1 +++ b/public/Set-DbaDbCompression.ps1 @@ -214,7 +214,7 @@ function Set-DbaDbCompression { } catch { Stop-Function -Message "Compression failed for $instance - $db - table $($obj.Schema).$($obj.Name) - partition $($p.PartitionNumber)" -Target $db -ErrorRecord $_ -Continue } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -258,7 +258,7 @@ function Set-DbaDbCompression { } catch { Stop-Function -Message "Compression failed for $instance - $db - table $($obj.Schema).$($obj.Name) - index $($index.Name) - partition $($p.PartitionNumber)" -Target $db -ErrorRecord $_ -Continue } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -300,7 +300,7 @@ function Set-DbaDbCompression { } catch { Stop-Function -Message "Compression failed for $instance - $db - table $($obj.Schema).$($obj.Name) - index $($index.Name) - partition $($p.PartitionNumber)" -Target $db -ErrorRecord $_ -Continue } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Set-DbaDbFileGrowth.ps1 b/public/Set-DbaDbFileGrowth.ps1 index bc59efa6b2..fc954f4cc8 100644 --- a/public/Set-DbaDbFileGrowth.ps1 +++ b/public/Set-DbaDbFileGrowth.ps1 @@ -85,7 +85,7 @@ function Set-DbaDbFileGrowth { [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] param ( [DbaInstanceParameter[]]$SqlInstance, - [PsCredential]$SqlCredential, + [PSCredential]$SqlCredential, [string[]]$Database, [ValidateSet("KB", "MB", "GB", "TB")] [string]$GrowthType = "MB", @@ -139,4 +139,4 @@ function Set-DbaDbFileGrowth { } } } -} +} \ No newline at end of file diff --git a/public/Set-DbaDbState.ps1 b/public/Set-DbaDbState.ps1 index 4a00d4d149..e8ce44a9f1 100644 --- a/public/Set-DbaDbState.ps1 +++ b/public/Set-DbaDbState.ps1 @@ -141,7 +141,7 @@ function Set-DbaDbState { [switch]$Force, [switch]$EnableException, [parameter(Mandatory, ValueFromPipeline, ParameterSetName = "Database")] - [PsCustomObject[]]$InputObject + [PSCustomObject[]]$InputObject ) begin { diff --git a/public/Set-DbaExtendedProtection.ps1 b/public/Set-DbaExtendedProtection.ps1 index bb094377cf..65714c9a10 100644 --- a/public/Set-DbaExtendedProtection.ps1 +++ b/public/Set-DbaExtendedProtection.ps1 @@ -138,7 +138,7 @@ function Set-DbaExtendedProtection { Set-ItemProperty -Path $regPath -Name ExtendedProtection -Value $Value $extendedProtection = (Get-ItemProperty -Path $regPath -Name ExtendedProtection).ExtendedProtection - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME InstanceName = $args[2] SqlInstance = $args[1] diff --git a/public/Set-DbaMaxDop.ps1 b/public/Set-DbaMaxDop.ps1 index b8e2f34271..f12c1a3aa2 100644 --- a/public/Set-DbaMaxDop.ps1 +++ b/public/Set-DbaMaxDop.ps1 @@ -92,7 +92,7 @@ function Set-DbaMaxDop { [object[]]$ExcludeDatabase, [int]$MaxDop = -1, [Parameter(ValueFromPipeline)] - [pscustomobject]$InputObject, + [PSCustomObject]$InputObject, [Alias("All")] [switch]$AllDatabases, [switch]$EnableException @@ -224,7 +224,7 @@ function Set-DbaMaxDop { } } - $results = [pscustomobject]@{ + $results = [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Set-DbaNetworkCertificate.ps1 b/public/Set-DbaNetworkCertificate.ps1 index 9edc2878cc..4aa35f82c8 100644 --- a/public/Set-DbaNetworkCertificate.ps1 +++ b/public/Set-DbaNetworkCertificate.ps1 @@ -227,7 +227,7 @@ function Set-DbaNetworkCertificate { $newThumbprint = (Get-ItemProperty -Path $regPath -Name Certificate).Certificate - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME InstanceName = $instanceName SqlInstance = $vsname diff --git a/public/Set-DbaNetworkConfiguration.ps1 b/public/Set-DbaNetworkConfiguration.ps1 index b2e235dc93..0d25ac2937 100644 --- a/public/Set-DbaNetworkConfiguration.ps1 +++ b/public/Set-DbaNetworkConfiguration.ps1 @@ -509,4 +509,4 @@ function Set-DbaNetworkConfiguration { } } } -} +} \ No newline at end of file diff --git a/public/Set-DbaPrivilege.ps1 b/public/Set-DbaPrivilege.ps1 index fa53de0dc1..ab050febb6 100644 --- a/public/Set-DbaPrivilege.ps1 +++ b/public/Set-DbaPrivilege.ps1 @@ -58,7 +58,7 @@ function Set-DbaPrivilege { param ( [parameter(ValueFromPipeline)] [Alias("cn", "host", "Server")] - [dbainstanceparameter[]]$ComputerName = $env:COMPUTERNAME, + [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME, [PSCredential]$Credential, [Parameter(Mandatory)] [ValidateSet('IFI', 'LPIM', 'BatchLogon', 'SecAudit', 'ServiceLogon')] diff --git a/public/Set-DbaResourceGovernor.ps1 b/public/Set-DbaResourceGovernor.ps1 index 502fef529a..01cd56e423 100644 --- a/public/Set-DbaResourceGovernor.ps1 +++ b/public/Set-DbaResourceGovernor.ps1 @@ -133,4 +133,4 @@ function Set-DbaResourceGovernor { Get-DbaResourceGovernor -SqlInstance $server } } -} +} \ No newline at end of file diff --git a/public/Set-DbaRgResourcePool.ps1 b/public/Set-DbaRgResourcePool.ps1 index f4ec3021d5..0172fdf90f 100644 --- a/public/Set-DbaRgResourcePool.ps1 +++ b/public/Set-DbaRgResourcePool.ps1 @@ -231,4 +231,4 @@ function Set-DbaRgResourcePool { $respool | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, Id, Name, CapCpuPercentage, IsSystemObject, MaximumCpuPercentage, MaximumIopsPerVolume, MaximumMemoryPercentage, MinimumCpuPercentage, MinimumIopsPerVolume, MinimumMemoryPercentage, WorkloadGroups } } -} +} \ No newline at end of file diff --git a/public/Set-DbaSpConfigure.ps1 b/public/Set-DbaSpConfigure.ps1 index 403c815e1b..04e09f2b78 100644 --- a/public/Set-DbaSpConfigure.ps1 +++ b/public/Set-DbaSpConfigure.ps1 @@ -112,7 +112,7 @@ function Set-DbaSpConfigure { $configobject.Property.ConfigValue = $value $server.Configuration.Alter() - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Set-DbaSpn.ps1 b/public/Set-DbaSpn.ps1 index d74661f06c..8d73920b4b 100644 --- a/public/Set-DbaSpn.ps1 +++ b/public/Set-DbaSpn.ps1 @@ -121,7 +121,7 @@ function Set-DbaSpn { $delegate = $false } - [pscustomobject]@{ + [PSCustomObject]@{ Name = $spn ServiceAccount = $ServiceAccount Property = "servicePrincipalName" @@ -147,7 +147,7 @@ function Set-DbaSpn { $status = "Failed to add constrained delegation" } - [pscustomobject]@{ + [PSCustomObject]@{ Name = $spn ServiceAccount = $ServiceAccount Property = "msDS-AllowedToDelegateTo" diff --git a/public/Set-DbaTcpPort.ps1 b/public/Set-DbaTcpPort.ps1 index 9acf5e8f6e..0ef22186f8 100644 --- a/public/Set-DbaTcpPort.ps1 +++ b/public/Set-DbaTcpPort.ps1 @@ -135,4 +135,4 @@ function Set-DbaTcpPort { } } } -} +} \ No newline at end of file diff --git a/public/Start-DbaMigration.ps1 b/public/Start-DbaMigration.ps1 index 157a81a246..8b968620b2 100644 --- a/public/Start-DbaMigration.ps1 +++ b/public/Start-DbaMigration.ps1 @@ -506,4 +506,4 @@ function Start-DbaMigration { Write-Message -Level Verbose -Message "Migration completed: $(Get-Date)" Write-Message -Level Verbose -Message "Total Elapsed time: $totaltime" } -} +} \ No newline at end of file diff --git a/public/Stop-DbaProcess.ps1 b/public/Stop-DbaProcess.ps1 index cb600604a5..cc943f39d6 100644 --- a/public/Stop-DbaProcess.ps1 +++ b/public/Stop-DbaProcess.ps1 @@ -140,7 +140,7 @@ function Stop-DbaProcess { if ($Pscmdlet.ShouldProcess($sourceserver, "Killing spid $currentspid")) { try { $sourceserver.KillProcess($currentspid) - [pscustomobject]@{ + [PSCustomObject]@{ SqlInstance = $sourceserver.name Spid = $session.Spid Login = $session.Login diff --git a/public/Sync-DbaAvailabilityGroup.ps1 b/public/Sync-DbaAvailabilityGroup.ps1 index 34b75d088d..aecdbda942 100644 --- a/public/Sync-DbaAvailabilityGroup.ps1 +++ b/public/Sync-DbaAvailabilityGroup.ps1 @@ -201,7 +201,7 @@ function Sync-DbaAvailabilityGroup { } } - $thiscombo = [pscustomobject]@{ + $thiscombo = [PSCustomObject]@{ PrimaryServer = $server SecondaryServer = $secondaries } diff --git a/public/Sync-DbaLoginPermission.ps1 b/public/Sync-DbaLoginPermission.ps1 index 1c293cc406..6cc3590ce1 100644 --- a/public/Sync-DbaLoginPermission.ps1 +++ b/public/Sync-DbaLoginPermission.ps1 @@ -131,7 +131,7 @@ function Sync-DbaLoginPermission { } - $copyLoginPermissionStatus = [pscustomobject]@{ + $copyLoginPermissionStatus = [PSCustomObject]@{ SourceServer = $sourceserver.Name DestinationServer = $destServer.Name Name = $loginName diff --git a/public/Test-DbaAgSpn.ps1 b/public/Test-DbaAgSpn.ps1 index e7908309dd..295b31d4ee 100644 --- a/public/Test-DbaAgSpn.ps1 +++ b/public/Test-DbaAgSpn.ps1 @@ -93,7 +93,7 @@ function Test-DbaAgSpn { if (-not $Listener) { $listeners = $ag | Get-DbaAgListener } else { - write-warning poot + Write-Warning poot $listeners = $ag | Get-DbaAgListener -Listener $Listener } @@ -115,7 +115,7 @@ function Test-DbaAgSpn { $required = "MSSQLSvc/" + $hostEntry + ":" + $aglistener.InstanceName } - $spns += [pscustomobject] @{ + $spns += [PSCustomObject] @{ ComputerName = $server.Information.FullyQualifiedNetName SqlInstance = $aglistener.SqlInstance InstanceName = $aglistener.InstanceName @@ -132,7 +132,7 @@ function Test-DbaAgSpn { Credential = $Credential } - $spns += [pscustomobject] @{ + $spns += [PSCustomObject] @{ ComputerName = $server.Information.FullyQualifiedNetName SqlInstance = $aglistener.SqlInstance InstanceName = $aglistener.InstanceName diff --git a/public/Test-DbaBackupEncrypted.ps1 b/public/Test-DbaBackupEncrypted.ps1 index 84b7243dbd..d0c58d81df 100644 --- a/public/Test-DbaBackupEncrypted.ps1 +++ b/public/Test-DbaBackupEncrypted.ps1 @@ -104,7 +104,7 @@ function Test-DbaBackupEncrypted { } Write-Message -Level Verbose -Message "Checking $file" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Test-DbaConnection.ps1 b/public/Test-DbaConnection.ps1 index d9fd9fb533..9be746f8bd 100644 --- a/public/Test-DbaConnection.ps1 +++ b/public/Test-DbaConnection.ps1 @@ -108,9 +108,14 @@ function Test-DbaConnection { ) process { foreach ($instance in $SqlInstance) { + # Clear loop variables assigned after connection test - https://github.com/dataplat/dbatools/issues/9066 + $authType = $null + $tcpport = $null + $authscheme = $null + # Get local environment Write-Message -Level Verbose -Message "Getting local environment information" - $localInfo = [pscustomobject]@{ + $localInfo = [PSCustomObject]@{ Windows = [environment]::OSVersion.Version.ToString() Edition = $PSVersionTable.PSEdition PowerShell = $PSVersionTable.PSVersion.ToString() @@ -223,4 +228,4 @@ function Test-DbaConnection { } } } -} +} \ No newline at end of file diff --git a/public/Test-DbaConnectionAuthScheme.ps1 b/public/Test-DbaConnectionAuthScheme.ps1 index 4bf2737990..1df9f1b55a 100644 --- a/public/Test-DbaConnectionAuthScheme.ps1 +++ b/public/Test-DbaConnectionAuthScheme.ps1 @@ -116,4 +116,4 @@ function Test-DbaConnectionAuthScheme { } } } -} +} \ No newline at end of file diff --git a/public/Test-DbaDbCompatibility.ps1 b/public/Test-DbaDbCompatibility.ps1 index bef32d0c7b..0648475600 100644 --- a/public/Test-DbaDbCompatibility.ps1 +++ b/public/Test-DbaDbCompatibility.ps1 @@ -77,7 +77,8 @@ function Test-DbaDbCompatibility { Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue } - $serverLevel = [Microsoft.SqlServer.Management.Smo.CompatibilityLevel]$server.Databases['master'].CompatibilityLevel + $serverVersion = $server.VersionMajor + $serverLevel = [Microsoft.SqlServer.Management.Smo.CompatibilityLevel]"Version$($serverVersion)0" $dbs = $server.Databases if ($Database) { diff --git a/public/Test-DbaDbCompression.ps1 b/public/Test-DbaDbCompression.ps1 index 27ed0496bc..5bc764d648 100644 --- a/public/Test-DbaDbCompression.ps1 +++ b/public/Test-DbaDbCompression.ps1 @@ -61,7 +61,7 @@ function Test-DbaDbCompression { Accepts a DbaInstanceParameter. Any collection of SQL Server Instance names or SMO objects can be piped to command. .OUTPUTS - Returns a PsCustomObject with following fields: ComputerName, InstanceName, SqlInstance, Database, IndexName, Partition, IndexID, PercentScan, PercentUpdate, RowEstimatePercentOriginal, PageEstimatePercentOriginal, CompressionTypeRecommendation, SizeCurrent, SizeRequested, PercentCompression + Returns a PSCustomObject with following fields: ComputerName, InstanceName, SqlInstance, Database, IndexName, Partition, IndexID, PercentScan, PercentUpdate, RowEstimatePercentOriginal, PageEstimatePercentOriginal, CompressionTypeRecommendation, SizeCurrent, SizeRequested, PercentCompression .NOTES Tags: Compression, Table diff --git a/public/Test-DbaDbDataMaskingConfig.ps1 b/public/Test-DbaDbDataMaskingConfig.ps1 index d0b28d3a68..34ea09dfa5 100644 --- a/public/Test-DbaDbDataMaskingConfig.ps1 +++ b/public/Test-DbaDbDataMaskingConfig.ps1 @@ -310,4 +310,4 @@ function Test-DbaDbDataMaskingConfig { } # End for each column } # End for each table } -} +} \ No newline at end of file diff --git a/public/Test-DbaDbOwner.ps1 b/public/Test-DbaDbOwner.ps1 index f1f22cfcce..dee8714de5 100644 --- a/public/Test-DbaDbOwner.ps1 +++ b/public/Test-DbaDbOwner.ps1 @@ -101,7 +101,7 @@ function Test-DbaDbOwner { } Write-Message -Level Verbose -Message "Checking $db" - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Test-DbaDiskAlignment.ps1 b/public/Test-DbaDiskAlignment.ps1 index 963c14c57b..cf3f75cc63 100644 --- a/public/Test-DbaDiskAlignment.ps1 +++ b/public/Test-DbaDiskAlignment.ps1 @@ -310,4 +310,4 @@ function Test-DbaDiskAlignment { } } } -} +} \ No newline at end of file diff --git a/public/Test-DbaEndpoint.ps1 b/public/Test-DbaEndpoint.ps1 index 10af99aae5..ab6bb2bb87 100644 --- a/public/Test-DbaEndpoint.ps1 +++ b/public/Test-DbaEndpoint.ps1 @@ -113,7 +113,7 @@ function Test-DbaEndpoint { $sslconnect = $_ } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $end.ComputerName InstanceName = $end.InstanceName SqlInstance = $end.SqlInstance diff --git a/public/Test-DbaLastBackup.ps1 b/public/Test-DbaLastBackup.ps1 index ab2bec4fcd..64ec48871c 100644 --- a/public/Test-DbaLastBackup.ps1 +++ b/public/Test-DbaLastBackup.ps1 @@ -84,7 +84,7 @@ function Test-DbaLastBackup { If this switch is enabled, transaction log backups will be ignored. The restore will stop at the latest full or differential backup point. .PARAMETER IgnoreDiffBackup - If this switch is enabled, differential backuys will be ignored. The restore will only use Full and Log backups, so will take longer to complete + If this switch is enabled, differential backups will be ignored. The restore will only use Full and Log backups, so will take longer to complete .PARAMETER Prefix The database is restored as "dbatools-testrestore-$databaseName" by default. You can change dbatools-testrestore to whatever you would like using this parameter. @@ -100,12 +100,12 @@ function Test-DbaLastBackup { .PARAMETER MaxTransferSize Parameter to set the unit of transfer. Values must be a multiple of 64kb and a max of 4GB - Parameter is used as passtrough for Restore-DbaDatabase. + Parameter is used as passthrough for Restore-DbaDatabase. .PARAMETER BufferCount Number of I/O buffers to use to perform the operation. - Refererence: https://msdn.microsoft.com/en-us/library/ms178615.aspx#data-transfer-options - Parameter is used as passtrough for Restore-DbaDatabase. + Reference: https://msdn.microsoft.com/en-us/library/ms178615.aspx#data-transfer-options + Parameter is used as passthrough for Restore-DbaDatabase. .PARAMETER ReuseSourceFolderStructure By default, databases will be migrated to the destination Sql Server's default data and log directories. You can override this by specifying -ReuseSourceFolderStructure. @@ -178,7 +178,7 @@ function Test-DbaLastBackup { Determines the last full backup for ALL databases, attempts to restore all databases (with a different name and file structure). The Restore will use more memory for reading the backup files. Do not set these values to high or you can get an Out of Memory error!!! - When running the restore with these additional parameters and there is other server activity it could affect server OLTP performance. Please use with causion. + When running the restore with these additional parameters and there is other server activity it could affect server OLTP performance. Please use with caution. Prior to running, you should check memory and server resources before configure it to run automatically. More information: https://www.mssqltips.com/sqlservertip/4935/optimize-sql-server-database-restore-performance/ @@ -243,7 +243,7 @@ function Test-DbaLastBackup { } if ($db.LastFullBackup.Year -eq 1) { - [pscustomobject]@{ + [PSCustomObject]@{ SourceServer = $source TestServer = $destination Database = $db.name @@ -346,7 +346,7 @@ function Test-DbaLastBackup { $totalSizeMB = ($lastbackup.TotalSize.Megabyte | Measure-Object -Sum).Sum if ($MaxSize -and $MaxSize -lt $totalSizeMB) { - [pscustomobject]@{ + [PSCustomObject]@{ SourceServer = $source TestServer = $destination Database = $db.name @@ -361,7 +361,7 @@ function Test-DbaLastBackup { DbccStart = $null DbccEnd = $null DbccElapsed = $null - BackupDates = [String[]]($lastbackup.Start) + BackupDates = [dbadatetime[]]($lastbackup.Start) BackupFiles = $lastbackup.FullName } continue @@ -540,7 +540,7 @@ function Test-DbaLastBackup { } if (-not $NoDrop -and $null -ne $destserver.databases[$dbName]) { - if ($Pscmdlet.ShouldProcess($dbName, "Dropping Database $dbName on $destination")) { + if ($PSCmdlet.ShouldProcess($dbName, "Dropping Database $dbName on $destination")) { Write-Message -Level Verbose -Message "Dropping database." ## Drop the database @@ -575,7 +575,7 @@ function Test-DbaLastBackup { } if ($Pscmdlet.ShouldProcess("console", "Showing results")) { - [pscustomobject]@{ + [PSCustomObject]@{ SourceServer = $source TestServer = $destination Database = $db.name @@ -590,7 +590,7 @@ function Test-DbaLastBackup { DbccStart = [dbadatetime]$startDbcc DbccEnd = [dbadatetime]$endDbcc DbccElapsed = $dbccElapsed - BackupDates = [String[]]($lastbackup.Start) + BackupDates = [dbadatetime[]]($lastbackup.Start) BackupFiles = $lastbackup.FullName } } diff --git a/public/Test-DbaLoginPassword.ps1 b/public/Test-DbaLoginPassword.ps1 index a87be7184e..e0d8ba07f0 100644 --- a/public/Test-DbaLoginPassword.ps1 +++ b/public/Test-DbaLoginPassword.ps1 @@ -82,39 +82,48 @@ function Test-DbaLoginPassword { ) begin { - $CheckPasses = "''", "'@@Name'" - if ($Dictionary) { - $Dictionary | ForEach-Object { $CheckPasses += "'" + $psitem + "'" } - } - foreach ($CheckPass in $CheckPasses) { - if ($CheckPasses.IndexOf($CheckPass) -eq 0) { - $checks = "SELECT " + $CheckPass - } else { - $checks += " - UNION SELECT " + $CheckPass + function Split-ArrayInChunks { + param( + [object[]] $source, + [int] $size = 1 + ) + $chunkCount = [Math]::Ceiling($source.Count / $size) + 0 .. ($chunkCount - 1) | ForEach-Object { + $startIndex = $_ * $size + $endIndex = [Math]::Min(($_ + 1) * $size, $source.Count) + , $source[$startIndex .. ($endIndex - 1)] } } - $sql = "DECLARE @WeakPwdList TABLE(WeakPwd NVARCHAR(255)) - --Define weak password list - --Use @@Name if users password contain their name - INSERT INTO @WeakPwdList(WeakPwd) - $checks - - SELECT SERVERPROPERTY('MachineName') AS [ComputerName], - ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName, - SERVERPROPERTY('ServerName') AS [SqlInstance], - SysLogins.name as SqlLogin, - WeakPassword = 'True', - REPLACE(WeakPassword.WeakPwd,'@@Name',SysLogins.name) As [Password], - SysLogins.is_disabled as Disabled, - SysLogins.create_date as CreatedDate, - SysLogins.modify_date as ModifiedDate, - SysLogins.default_database_name as DefaultDatabase - FROM sys.sql_logins SysLogins - INNER JOIN @WeakPwdList WeakPassword ON (PWDCOMPARE(WeakPassword.WeakPwd, password_hash) = 1 - OR PWDCOMPARE(REPLACE(WeakPassword.WeakPwd,'@@Name',SysLogins.name),password_hash) = 1)" + $maxBatch = 200 + + $CheckPasses = "", "@@Name" + if ($Dictionary) { + $Dictionary | ForEach-Object { $CheckPasses += $PSItem } + } + + $sqlStart = "DECLARE @WeakPwdList TABLE(WeakPwd NVARCHAR(255)) + --Define weak password list + --Use @@Name if users password contain their name + INSERT INTO @WeakPwdList(WeakPwd) + VALUES (NULL)" + + $sqlEnd = " + SELECT SERVERPROPERTY('MachineName') AS [ComputerName], + ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName, + SERVERPROPERTY('ServerName') AS [SqlInstance], + SysLogins.name as SqlLogin, + WeakPassword = 'True', + REPLACE(WeakPassword.WeakPwd,'@@Name',SysLogins.name) As [Password], + SysLogins.is_disabled as Disabled, + SysLogins.create_date as CreatedDate, + SysLogins.modify_date as ModifiedDate, + SysLogins.default_database_name as DefaultDatabase + FROM sys.sql_logins SysLogins + INNER JOIN @WeakPwdList WeakPassword + ON PWDCOMPARE(REPLACE(WeakPassword.WeakPwd,'@@Name',SysLogins.name),password_hash) = 1 + " } process { foreach ($instance in $SqlInstance) { @@ -130,14 +139,29 @@ function Test-DbaLoginPassword { } end { $servers = $logins | Select-Object -Unique -ExpandProperty Parent - $names = $logins | Select-Object -Unique -ExpandProperty Name foreach ($serverinstance in $servers) { - Write-Message -Level Debug -Message "Executing $sql" Write-Message -Level Verbose -Message "Testing: same username as Password" Write-Message -Level Verbose -Message "Testing: the following Passwords $CheckPasses" try { - $serverinstance.Query("$sql") | Where-Object SqlLogin -in $names + $checkParts = , (Split-ArrayInChunks -source $CheckPasses -size $maxBatch) + + $loopIndex = 0 + + foreach ($batch in $checkParts) { + $thisBatch = $sqlStart + $sqlParams = @{ } + foreach ($piece in $batch) { + $loopIndex += 1 + $paramKey = "@p_$loopIndex" + $sqlParams[$paramKey] = $piece + $thisBatch += ", ($paramKey)" + } + $thisBatch += $sqlEnd + Write-Message -Level Debug -Message "sql: $thisBatch" + Invoke-DbaQuery -SqlInstance $serverinstance -Query $thisBatch -SqlParameter $sqlParams + } + } catch { Stop-Function -Message "Failure" -ErrorRecord $_ -Target $serverinstance -Continue } diff --git a/public/Test-DbaManagementObject.ps1 b/public/Test-DbaManagementObject.ps1 index c7530b4fea..51fdee7fcf 100644 --- a/public/Test-DbaManagementObject.ps1 +++ b/public/Test-DbaManagementObject.ps1 @@ -56,13 +56,13 @@ function Test-DbaManagementObject { } if ($smoList) { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME Version = $number Exists = $true } } else { - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME Version = $number Exists = $false diff --git a/public/Test-DbaMaxDop.ps1 b/public/Test-DbaMaxDop.ps1 index fdfe7ee0df..8ae6150a52 100644 --- a/public/Test-DbaMaxDop.ps1 +++ b/public/Test-DbaMaxDop.ps1 @@ -161,7 +161,7 @@ function Test-DbaMaxDop { } } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName @@ -192,7 +192,7 @@ function Test-DbaMaxDop { $dbmaxdop = $database.MaxDop - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Test-DbaMaxMemory.ps1 b/public/Test-DbaMaxMemory.ps1 index f6cceebdda..32827d84c8 100644 --- a/public/Test-DbaMaxMemory.ps1 +++ b/public/Test-DbaMaxMemory.ps1 @@ -129,7 +129,7 @@ function Test-DbaMaxMemory { $recommendedMax = $recommendedMax / $instanceCount - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Test-DbaMigrationConstraint.ps1 b/public/Test-DbaMigrationConstraint.ps1 index 88524343c1..b7a009a296 100644 --- a/public/Test-DbaMigrationConstraint.ps1 +++ b/public/Test-DbaMigrationConstraint.ps1 @@ -190,7 +190,7 @@ function Test-DbaMigrationConstraint { $fileStreamDestination = Get-DbaSpConfigure -SqlInstance $destServer -ConfigName FilestreamAccessLevel if ($fileStreamSource.RunningValue -ne $fileStreamDestination.RunningValue) { - [pscustomobject]@{ + [PSCustomObject]@{ SourceInstance = $sourceServer.Name DestinationInstance = $destServer.Name SourceVersion = $sourceVersion @@ -229,7 +229,7 @@ function Test-DbaMigrationConstraint { This means that database cannot be migrated because Express edition doesn't have SQL Server Agent #> if ($editions.Item($destServer.Edition.ToString().Split(" ")[0]) -eq 1 -and $dbFeatures.Contains("ChangeCapture")) { - [pscustomobject]@{ + [PSCustomObject]@{ SourceInstance = $sourceServer.Name DestinationInstance = $destServer.Name SourceVersion = $sourceVersion @@ -240,7 +240,7 @@ function Test-DbaMigrationConstraint { Notes = "$notesCannotMigrate. Destination server edition is EXPRESS which does not support 'ChangeCapture' feature that is in use." } } else { - [pscustomobject]@{ + [PSCustomObject]@{ SourceInstance = $sourceServer.Name DestinationInstance = $destServer.Name SourceVersion = $sourceVersion @@ -259,7 +259,7 @@ function Test-DbaMigrationConstraint { #Check for editions. If destination edition is lower than source edition and exists features in use if (($editions.Item($destServer.Edition.ToString().Split(" ")[0]) -lt $editions.Item($sourceServer.Edition.ToString().Split(" ")[0])) -and (!([string]::IsNullOrEmpty($dbFeatures)))) { - [pscustomobject]@{ + [PSCustomObject]@{ SourceInstance = $sourceServer.Name DestinationInstance = $destServer.Name SourceVersion = $sourceVersion @@ -272,7 +272,7 @@ function Test-DbaMigrationConstraint { } # else { - [pscustomobject]@{ + [PSCustomObject]@{ SourceInstance = $sourceServer.Name DestinationInstance = $destServer.Name SourceVersion = $sourceVersion diff --git a/public/Test-DbaOptimizeForAdHoc.ps1 b/public/Test-DbaOptimizeForAdHoc.ps1 index f626020f2d..d4b823c493 100644 --- a/public/Test-DbaOptimizeForAdHoc.ps1 +++ b/public/Test-DbaOptimizeForAdHoc.ps1 @@ -73,7 +73,7 @@ function Test-DbaOptimizeForAdHoc { $notes = $notesAdHocZero } - [pscustomobject]@{ + [PSCustomObject]@{ ComputerName = $server.ComputerName InstanceName = $server.ServiceName SqlInstance = $server.DomainInstanceName diff --git a/public/Test-DbaPath.ps1 b/public/Test-DbaPath.ps1 index 9bf2df8957..4304725742 100644 --- a/public/Test-DbaPath.ps1 +++ b/public/Test-DbaPath.ps1 @@ -64,7 +64,7 @@ function Test-DbaPath { } catch { Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue } - $counter = [pscustomobject] @{ Value = 0 } + $counter = [PSCustomObject] @{ Value = 0 } $groupSize = 100 $RawPath = $Path $Path = [string[]]$Path @@ -87,7 +87,7 @@ function Test-DbaPath { $i = 0 foreach ($r in $batchresult.tables.rows) { $DoesPass = $r[0] -eq $true -or $r[1] -eq $true - [pscustomobject]@{ + [PSCustomObject]@{ SqlInstance = $server.Name InstanceName = $server.ServiceName ComputerName = $server.ComputerName diff --git a/public/Test-DbaRepLatency.ps1 b/public/Test-DbaReplLatency.ps1 similarity index 95% rename from public/Test-DbaRepLatency.ps1 rename to public/Test-DbaReplLatency.ps1 index 6224e0041a..aff54d33a1 100644 --- a/public/Test-DbaRepLatency.ps1 +++ b/public/Test-DbaReplLatency.ps1 @@ -1,4 +1,4 @@ -function Test-DbaRepLatency { +function Test-DbaReplLatency { <# .SYNOPSIS Displays replication latency for all transactional publications for a server or database. @@ -50,20 +50,20 @@ function Test-DbaRepLatency { License: MIT https://opensource.org/licenses/MIT .LINK - https://dbatools.io/Test-DbaRepLatency + https://dbatools.io/Test-DbaReplLatency .EXAMPLE - PS C:\> Test-DbaRepLatency -SqlInstance sql2008, sqlserver2012 + PS C:\> Test-DbaReplLatency -SqlInstance sql2008, sqlserver2012 Return replication latency for all transactional publications for servers sql2008 and sqlserver2012. .EXAMPLE - PS C:\> Test-DbaRepLatency -SqlInstance sql2008 -Database TestDB + PS C:\> Test-DbaReplLatency -SqlInstance sql2008 -Database TestDB Return replication latency for all transactional publications on server sql2008 for only the TestDB database .EXAMPLE - PS C:\> Test-DbaRepLatency -SqlInstance sql2008 -Database TestDB -PublicationName TestDB_Pub + PS C:\> Test-DbaReplLatency -SqlInstance sql2008 -Database TestDB -PublicationName TestDB_Pub Return replication latency for the TestDB_Pub publication for the TestDB database located on the server sql2008. @@ -94,7 +94,7 @@ function Test-DbaRepLatency { Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue } - $publicationNames = Get-DbaRepPublication -SqlInstance $server -Database $Database -SqlCredential $SqlCredentials -PublicationType "Transactional" + $publicationNames = Get-DbaReplPublication -SqlInstance $server -Database $Database -SqlCredential $SqlCredentials -Type "Transactional" if ($PublicationName) { $publicationNames = $publicationNames | Where-Object PublicationName -in $PublicationName @@ -205,7 +205,7 @@ function Test-DbaRepLatency { PublicationServer = $publication.Server PublicationDB = $publication.Database PublicationName = $publication.PublicationName - PublicationType = $publication.PublicationType + PublicationType = $publication.Type DistributionServer = $distributionServer DistributionDB = $distributionDatabase SubscriberServer = $info.subscriber @@ -213,7 +213,7 @@ function Test-DbaRepLatency { PublisherToDistributorLatency = $info.distributor_latency DistributorToSubscriberLatency = $info.subscriber_latency TotalLatency = $totalLatency - } | Select-DefaultView -ExcludeProperty PublicationType + } | Select-DefaultView -ExcludeProperty Type if (!$RetainToken) { diff --git a/public/Test-DbaSpn.ps1 b/public/Test-DbaSpn.ps1 index efc0c11f2a..3f66a59a9c 100644 --- a/public/Test-DbaSpn.ps1 +++ b/public/Test-DbaSpn.ps1 @@ -93,7 +93,7 @@ function Test-DbaSpn { Write-Verbose "Found $instanceCount instances" foreach ($instance in $wmi.ServerInstances) { - $spn = [pscustomobject] @{ + $spn = [PSCustomObject] @{ ComputerName = $servereName InstanceName = $instanceName #SKUNAME diff --git a/public/Unregister-DbatoolsConfig.ps1 b/public/Unregister-DbatoolsConfig.ps1 index 28ec511751..7d467f4bab 100644 --- a/public/Unregister-DbatoolsConfig.ps1 +++ b/public/Unregister-DbatoolsConfig.ps1 @@ -102,7 +102,7 @@ function Unregister-DbatoolsConfig { $fileUserLocalSettings = @() if (Test-Path (Join-Path $script:path_FileUserLocal "psf_config.json")) { $fileUserLocalSettings = Get-Content (Join-Path $script:path_FileUserLocal "psf_config.json") -Encoding UTF8 | ConvertFrom-Json } if ($fileUserLocalSettings) { - $pathProperties += [pscustomobject]@{ + $pathProperties += [PSCustomObject]@{ Path = (Join-Path $script:path_FileUserLocal "psf_config.json") Properties = $fileUserLocalSettings Changed = $false @@ -113,7 +113,7 @@ function Unregister-DbatoolsConfig { $fileUserSharedSettings = @() if (Test-Path (Join-Path $script:path_FileUserShared "psf_config.json")) { $fileUserSharedSettings = Get-Content (Join-Path $script:path_FileUserShared "psf_config.json") -Encoding UTF8 | ConvertFrom-Json } if ($fileUserSharedSettings) { - $pathProperties += [pscustomobject]@{ + $pathProperties += [PSCustomObject]@{ Path = (Join-Path $script:path_FileUserShared "psf_config.json") Properties = $fileUserSharedSettings Changed = $false @@ -124,7 +124,7 @@ function Unregister-DbatoolsConfig { $fileSystemSettings = @() if (Test-Path (Join-Path $script:path_FileSystem "psf_config.json")) { $fileSystemSettings = Get-Content (Join-Path $script:path_FileSystem "psf_config.json") -Encoding UTF8 | ConvertFrom-Json } if ($fileSystemSettings) { - $pathProperties += [pscustomobject]@{ + $pathProperties += [PSCustomObject]@{ Path = (Join-Path $script:path_FileSystem "psf_config.json") Properties = $fileSystemSettings Changed = $false diff --git a/public/Update-DbaInstance.ps1 b/public/Update-DbaInstance.ps1 index 285fd15651..bf91777a4a 100644 --- a/public/Update-DbaInstance.ps1 +++ b/public/Update-DbaInstance.ps1 @@ -189,7 +189,7 @@ function Update-DbaInstance { [parameter(ValueFromPipeline, Position = 1)] [Alias("cn", "host", "Server")] [DbaInstanceParameter[]]$ComputerName = $env:COMPUTERNAME, - [pscredential]$Credential, + [PSCredential]$Credential, [Parameter(ParameterSetName = 'Version')] [ValidateNotNullOrEmpty()] [string[]]$Version, @@ -535,7 +535,7 @@ function Update-DbaInstance { Write-ProgressHelper -ExcludePercent -Activity $activity -Message "Preparing installation" $chosenVersions = ($upgrades | ForEach-Object { "$($_.MajorVersion) to $($_.TargetLevel) (KB$($_.KB))" }) -join ', ' if ($PSCmdlet.ShouldProcess($resolvedName, "Update $chosenVersions")) { - $installActions += [pscustomobject]@{ + $installActions += [PSCustomObject]@{ ComputerName = $resolvedName Actions = $upgrades } @@ -617,4 +617,4 @@ function Update-DbaInstance { $installActions | Invoke-Parallel -ImportModules -ImportVariables -ScriptBlock $installScript -Throttle $Throttle | ForEach-Object -Process $outputHandler } } -} +} \ No newline at end of file diff --git a/public/Update-DbaServiceAccount.ps1 b/public/Update-DbaServiceAccount.ps1 index 6753fdc176..13ac7d1b44 100644 --- a/public/Update-DbaServiceAccount.ps1 +++ b/public/Update-DbaServiceAccount.ps1 @@ -6,6 +6,8 @@ function Update-DbaServiceAccount { .DESCRIPTION Reconfigure the service account or update the password of the specified SQL Server service. The service will be restarted in the event of changing the account. + The command is only supported for SQL Server engine and agent service of supported versions of SQL Server. It might fail for older versions or other services. + .PARAMETER ComputerName The target SQL Server instance or instances. @@ -283,4 +285,4 @@ function Update-DbaServiceAccount { } } } -} +} \ No newline at end of file diff --git a/public/Write-DbaDbTableData.ps1 b/public/Write-DbaDbTableData.ps1 index a5310508f3..f2f8b28e31 100644 --- a/public/Write-DbaDbTableData.ps1 +++ b/public/Write-DbaDbTableData.ps1 @@ -761,4 +761,4 @@ function Write-DbaDbTableData { $context.ExecuteNonQuery("use [$originalDatabaseName]") } } -} +} \ No newline at end of file diff --git a/testing.ps1 b/testing.ps1 new file mode 100644 index 0000000000..842d9de1e1 --- /dev/null +++ b/testing.ps1 @@ -0,0 +1,271 @@ +############################## +# create docker environment +############################## +# create a shared network +docker network create localnet + +# Expose engines and setup shared path for migrations +docker run -p 2500:1433 --volume shared:/shared:z --name mssql1 --hostname mssql1 --network localnet -d dbatools/sqlinstance +docker run -p 2600:1433 --volume shared:/shared:z --name mssql2 --hostname mssql2 --network localnet -d dbatools/sqlinstance2 + +# create the repl folder +docker exec mssql1 mkdir /var/opt/mssql/ReplData + +# also need these folders for setting up replication +docker exec mssql1 mkdir /shared/data /shared/repldata + +############################## +# import our working module +############################## +Import-Module .\dbatools.psd1 -Force +Get-module dbatools* + +############################## +# create alias +############################## +New-DbaClientAlias -ServerName 'localhost,2500' -Alias mssql1 +New-DbaClientAlias -ServerName 'localhost,2600' -Alias mssql2 + + +############################## +# save the password for ease +############################## +$securePassword = ('dbatools.IO' | ConvertTo-SecureString -AsPlainText -Force) +$credential = New-Object System.Management.Automation.PSCredential('sqladmin', $securePassword) + +$PSDefaultParameterValues = @{ + "*:SqlCredential" = $credential + "*:DestinationCredential" = $credential + "*:DestinationSqlCredential" = $credential + "*:SourceSqlCredential" = $credential + "*:PublisherSqlCredential" = $credential +} + + +############################## +# change silly defaults +############################## +Set-DbatoolsConfig -FullName sql.connection.trustcert -Value $true -PassThru | Register-DbatoolsConfig #-Scope SystemMandatory +Set-DbatoolsConfig -FullName sql.connection.EncryptConnection -Value optional -PassThru | Register-DbatoolsConfig #-Scope SystemMandatory + +############################## +# test things :) +############################## + + +## already existing commands +<# +Get-DbaReplServer +Get-DbaReplDistributor +Get-DbaReplPublication +Test-DbaReplLatency + +Export-DbaReplServerSetting +#> + +$sqlInstance = Connect-DbaInstance -SqlInstance mssql1 + +Get-DbaReplServer -SqlInstance mssql1 +Get-DbaReplDistributor -SqlInstance mssql1 +Get-DbaReplPublication -SqlInstance mssql1 + +# enable\disable distribution +Enable-DbaReplDistributor -SqlInstance mssql1 +Disable-DbaReplDistributor -SqlInstance mssql1 + +Get-DbaReplDistributor -SqlInstance + +# enable publishing +Enable-DbaReplPublishing -SqlInstance mssql1 +Disable-DbaReplPublishing -SqlInstance mssql1 + +# add a transactional publication +$pub = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'testPub' + Type = 'Transactional' + +} +New-DbaReplPublication @pub -verbose + + + +# add a merge publication +$pub = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'mergey' + Type = 'Merge' + +} +New-DbaReplPublication @pub + +# add a snapshot publication +$pub = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'snappy' + Type = 'Snapshot' + +} +New-DbaReplPublication @pub + + +# add an article + +$article = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'testpub' + Name = 'publishers' + Filter = "city = 'seattle'" +} +Add-DbaReplArticle @article + +$article = @{ + SqlInstance = 'mssql1' + Database = 'ReplDb' + PublicationName = 'testtrans' + Name = 'ReplicateMe' +} +Add-DbaReplArticle @article -EnableException + +# mergey +$article = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'Mergey' + Name = 'publishers' + #Filter = "city = 'seattle'" ## not working? +} +Add-DbaReplArticle @article + +# snappy +$article = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'snappy' + Name = 'publishers' +} +Add-DbaReplArticle @article + + +# remove an article +$article = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'testpub' + Name = 'publishers' +} +Remove-DbaReplArticle @article + +# remove an article +$article = @{ + SqlInstance = 'mssql1' + Database = 'pubs' + PublicationName = 'Mergey' + Name = 'publishers' +} +Remove-DbaReplArticle @article + + + +## remove pubs +$pub = @{ + SqlInstance = 'mssql1' + Database = 'ReplDb' + Name = 'Snappy' +} +Remove-DbaReplPublication @pub +## remove pubs +$pub = @{ + SqlInstance = 'mssql1' + Database = 'ReplDb' + Name = 'TestPub' +} +Remove-DbaReplPublication @pub +## remove pubs +$pub = @{ + SqlInstance = 'mssql1' + Database = 'ReplDb' + Name = 'Mergey' +} +Remove-DbaReplPublication @pub + + + +# add subscriptions. + +#transactional +$sub = @{ + SqlInstance = 'mssql2' + Database = 'pubs' + PublicationDatabase = 'pubs' + PublisherSqlInstance = 'mssql1' + PublicationName = 'testpub' + Type = 'Push' + SubscriptionSqlCredential = $credential + +} +New-DbaReplSubscription @sub -enableexception + +#merge +$sub = @{ + SqlInstance = 'mssql2' + Database = 'Mergeypubs' + PublicationDatabase = 'pubs' + PublisherSqlInstance = 'mssql1' + PublicationName = 'Mergey' + Type = 'Push' + SubscriptionSqlCredential = $credential + +} +New-DbaReplSubscription @sub + +#snapshot +$sub = @{ + SqlInstance = 'mssql2' + Database = 'Snappypubs' + PublicationDatabase = 'pubs' + PublisherSqlInstance = 'mssql1' + PublicationName = 'Snappy' + Type = 'Push' + SubscriptionSqlCredential = $credential +} +New-DbaReplSubscription @sub + + +# remove subscriptions +$sub = @{ + SqlInstance = 'mssql2' + SubscriptionDatabase = 'pubs' + PublisherSqlInstance = 'mssql1' + PublicationDatabase = 'pubs' + PublicationName = 'testPub' +} +Remove-DbaReplSubscription @sub + +$sub = @{ + SqlInstance = 'mssql2' + SubscriptionDatabase = 'Mergeypubs' + PublisherSqlInstance = 'mssql1' + PublicationDatabase = 'pubs' + PublicationName = 'Mergey' +} +Remove-DbaReplSubscription @sub + +$sub = @{ + SqlInstance = 'mssql2' + PublisherSqlInstance = 'mssql1' + PublicationName = 'snappy' + PublicationDatabase = 'pubs' + SubscriptionDatabase = 'Snappypubs' +} +Remove-DbaReplSubscription @sub + +# TODO: Does the schema exist on the subscriber? +<# +// Ensure that we create the schema owner at the Subscriber. +article.SchemaOption |= CreationScriptOptions.Schema; +#> \ No newline at end of file diff --git a/tests/Add-DbaReplArticle.Tests.ps1 b/tests/Add-DbaReplArticle.Tests.ps1 new file mode 100644 index 0000000000..78d16d32ff --- /dev/null +++ b/tests/Add-DbaReplArticle.Tests.ps1 @@ -0,0 +1,17 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Publication', 'Schema', 'Name', 'Filter', 'CreationScriptOptions', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> \ No newline at end of file diff --git a/tests/Disable-DbaReplDistributor.Tests.ps1 b/tests/Disable-DbaReplDistributor.Tests.ps1 new file mode 100644 index 0000000000..8707c37e5a --- /dev/null +++ b/tests/Disable-DbaReplDistributor.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Force', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> \ No newline at end of file diff --git a/tests/Disable-DbaReplPublishing.Tests.ps1 b/tests/Disable-DbaReplPublishing.Tests.ps1 new file mode 100644 index 0000000000..db1d3ce2fd --- /dev/null +++ b/tests/Disable-DbaReplPublishing.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Force', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> diff --git a/tests/Enable-DbaReplDistributor.Tests.ps1 b/tests/Enable-DbaReplDistributor.Tests.ps1 new file mode 100644 index 0000000000..c1f08019a0 --- /dev/null +++ b/tests/Enable-DbaReplDistributor.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'DistributionDatabase', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> \ No newline at end of file diff --git a/tests/Enable-DbaReplPublishing.Tests.ps1 b/tests/Enable-DbaReplPublishing.Tests.ps1 new file mode 100644 index 0000000000..08143c6619 --- /dev/null +++ b/tests/Enable-DbaReplPublishing.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'SnapshotShare', 'PublisherSqlLogin', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> \ No newline at end of file diff --git a/tests/Export-DbaRepServerSetting.Tests.ps1 b/tests/Export-DbaReplServerSetting.Tests.ps1 similarity index 100% rename from tests/Export-DbaRepServerSetting.Tests.ps1 rename to tests/Export-DbaReplServerSetting.Tests.ps1 diff --git a/tests/Find-DbaInstance.Tests.ps1 b/tests/Find-DbaInstance.Tests.ps1 index a877984620..2903da74a3 100644 --- a/tests/Find-DbaInstance.Tests.ps1 +++ b/tests/Find-DbaInstance.Tests.ps1 @@ -24,9 +24,9 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { Context "Command finds SQL Server instances" { BeforeAll { if ($env:APPVEYOR) { - $results = Find-DbaInstance -ComputerName $script:instance3 -ScanType Browser, SqlConnect + $results = Find-DbaInstance -ComputerName $script:instance3 -ScanType Browser, SqlConnect | Select-Object -First 1 } else { - $results = Find-DbaInstance -ComputerName $TestServer -ScanType Browser, SqlConnect + $results = Find-DbaInstance -ComputerName $TestServer -ScanType Browser, SqlConnect | Select-Object -First 1 } } It "Returns an object type of [Dataplat.Dbatools.Discovery.DbaInstanceReport]" { @@ -42,4 +42,4 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $results.SqlConnected | Should -Be $true } } -} \ No newline at end of file +} diff --git a/tests/Get-DbaMemoryUsage.Tests.ps1 b/tests/Get-DbaMemoryUsage.Tests.ps1 index f744eb6b26..8be4bccca7 100644 --- a/tests/Get-DbaMemoryUsage.Tests.ps1 +++ b/tests/Get-DbaMemoryUsage.Tests.ps1 @@ -5,7 +5,7 @@ Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'ComputerName', 'Credential', 'EnableException' + [object[]]$knownParameters = 'ComputerName', 'Credential', 'MemoryCounterRegex', 'PlanCounterRegex', 'BufferCounterRegex', 'SSASCounterRegex', 'SSISCounterRegex', 'EnableException' $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters It "Should only contain our specific parameters" { (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 diff --git a/tests/Get-DbaReplArticle.Tests.ps1 b/tests/Get-DbaReplArticle.Tests.ps1 new file mode 100644 index 0000000000..11bdb49fd2 --- /dev/null +++ b/tests/Get-DbaReplArticle.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Publication', 'Schema', 'Name', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> \ No newline at end of file diff --git a/tests/Get-DbaReplArticleColumn.Tests.ps1 b/tests/Get-DbaReplArticleColumn.Tests.ps1 new file mode 100644 index 0000000000..3a5f07cf69 --- /dev/null +++ b/tests/Get-DbaReplArticleColumn.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Publication', 'Article', 'Column', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> \ No newline at end of file diff --git a/tests/Get-DbaRepDistributor.Tests.ps1 b/tests/Get-DbaReplDistributor.Tests.ps1 similarity index 93% rename from tests/Get-DbaRepDistributor.Tests.ps1 rename to tests/Get-DbaReplDistributor.Tests.ps1 index 2d4231cb8a..dded7c7e9d 100644 --- a/tests/Get-DbaRepDistributor.Tests.ps1 +++ b/tests/Get-DbaReplDistributor.Tests.ps1 @@ -15,7 +15,7 @@ Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { Context "ensuring accuracy of results" { - $results = Get-DbaRepDistributor -SqlInstance $script:instance1 + $results = Get-DbaReplDistributor -SqlInstance $script:instance1 It "accurately reports that the distributor is not installed" { $results.DistributorInstalled | Should Be $false } diff --git a/tests/Get-DbaRepPublication.Tests.ps1 b/tests/Get-DbaReplPublication.Tests.ps1 similarity index 55% rename from tests/Get-DbaRepPublication.Tests.ps1 rename to tests/Get-DbaReplPublication.Tests.ps1 index 57e1f5c9e4..fc06284fa7 100644 --- a/tests/Get-DbaRepPublication.Tests.ps1 +++ b/tests/Get-DbaReplPublication.Tests.ps1 @@ -4,11 +4,11 @@ Write-Host -Object "Running $PSCommandpath" -ForegroundColor Cyan Describe "$commandname Unit Tests" -Tag 'UnitTests' { Context "Validate parameters" { - [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} - [object[]]$knownParameters = 'SqlInstance', 'Database', 'SqlCredential', 'PublicationType', 'EnableException' + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Name', 'Type', 'EnableException' $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters It "Should only contain our specific parameters" { - (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 } } @@ -19,8 +19,9 @@ Describe "$commandname Unit Tests" -Tag 'UnitTests' { [object]@{ Name = 'TestDB' TransPublications = @{ - Name = 'TestDB_pub' - Type = 'Transactional' + Name = 'TestDB_pub' + Type = 'Transactional' + DatabaseName = 'TestDB' } MergePublications = @{} } @@ -28,32 +29,36 @@ Describe "$commandname Unit Tests" -Tag 'UnitTests' { Mock Connect-DbaInstance -MockWith { [object]@{ - Name = "MockServerName" - ComputerName = 'MockComputerName' - Databases = @{ + Name = "MockServerName" + ServiceName = 'MSSQLSERVER' + DomainInstanceName = 'MockServerName' + ComputerName = 'MockComputerName' + Databases = @{ Name = 'TestDB' #state #status ID = 5 ReplicationOptions = 'Published' + IsAccessible = $true + IsSystemObject = $false } - ConnectionContext = @{ + ConnectionContext = @{ SqlConnectionObject = 'FakeConnectionContext' } } } It "Honors the SQLInstance parameter" { - $Results = Get-DbaRepPublication -SqlInstance MockServerName - $Results.Server | Should Be "MockServerName" + $Results = Get-DbaReplPublication -SqlInstance MockServerName + $Results.SqlInstance.Name | Should Be "MockServerName" } It "Honors the Database parameter" { - $Results = Get-DbaRepPublication -SqlInstance MockServerName -Database TestDB - $Results.Database | Should Be "TestDB" + $Results = Get-DbaReplPublication -SqlInstance MockServerName -Database TestDB + $Results.DatabaseName | Should Be "TestDB" } - It "Honors the PublicationType parameter" { + It "Honors the Type parameter" { Mock Connect-ReplicationDB -MockWith { [object]@{ @@ -66,13 +71,13 @@ Describe "$commandname Unit Tests" -Tag 'UnitTests' { } } - $Results = Get-DbaRepPublication -SqlInstance MockServerName -Database TestDB -PublicationType Snapshot - $Results.PublicationType | Should Be "Snapshot" + $Results = Get-DbaReplPublication -SqlInstance MockServerName -Database TestDB -Type Snapshot + $Results.Type | Should Be "Snapshot" } - It "Stops if validate set for PublicationType is not met" { + It "Stops if validate set for Type is not met" { - { Get-DbaRepPublication -SqlInstance MockServerName -PublicationType NotAPubType } | should Throw + { Get-DbaReplPublication -SqlInstance MockServerName -Type NotAPubType } | should Throw } } diff --git a/tests/Get-DbaReplPublisher.Tests.ps1 b/tests/Get-DbaReplPublisher.Tests.ps1 new file mode 100644 index 0000000000..dde5fa4f51 --- /dev/null +++ b/tests/Get-DbaReplPublisher.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> \ No newline at end of file diff --git a/tests/Get-DbaRepServer.Tests.ps1 b/tests/Get-DbaReplServer.Tests.ps1 similarity index 100% rename from tests/Get-DbaRepServer.Tests.ps1 rename to tests/Get-DbaReplServer.Tests.ps1 diff --git a/tests/Get-DbaReplSubscription.Tests.ps1 b/tests/Get-DbaReplSubscription.Tests.ps1 new file mode 100644 index 0000000000..bee78c532f --- /dev/null +++ b/tests/Get-DbaReplSubscription.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm') } + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'PublicationName', 'SubscriberName', 'SubscriptionDatabase', 'Type', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> \ No newline at end of file diff --git a/tests/InModule.Help.Tests.ps1 b/tests/InModule.Help.Tests.ps1 index a9df2bc916..277981cc47 100644 --- a/tests/InModule.Help.Tests.ps1 +++ b/tests/InModule.Help.Tests.ps1 @@ -18,7 +18,9 @@ if ($env:appveyor) { 'Microsoft.SqlServer.Management.XEvent', 'Microsoft.SqlServer.Management.XEventDbScoped', 'Microsoft.SqlServer.Management.XEventDbScopedEnum', - 'Microsoft.SqlServer.Management.XEventEnum' + 'Microsoft.SqlServer.Management.XEventEnum', + 'Microsoft.SqlServer.Replication', + 'Microsoft.SqlServer.Rmo' ) foreach ($name in $names) { diff --git a/tests/New-DbaDbUser.Tests.ps1 b/tests/New-DbaDbUser.Tests.ps1 index 2350a3f129..b854ac6f94 100644 --- a/tests/New-DbaDbUser.Tests.ps1 +++ b/tests/New-DbaDbUser.Tests.ps1 @@ -44,7 +44,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { It "Creates the user and get it" { New-DbaDbUser -SqlInstance $script:instance2 -Database $dbname -Login $userName -DefaultSchema guest $newDbUser = Get-DbaDbUser -SqlInstance $script:instance2 -Database $dbname | Where-Object Name -eq $userName - $newDbUser.Name | Should Be $userName + $newDbUser.Name | Should -Be $userName $newDbUser.DefaultSchema | Should -Be 'guest' } } @@ -60,7 +60,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { It "Creates the user and get it. Login property is empty" { New-DbaDbUser -SqlInstance $script:instance2 -Database $dbname -User $userNameWithoutLogin -DefaultSchema guest $results = Get-DbaDbUser -SqlInstance $script:instance2 -Database $dbname | Where-Object Name -eq $userNameWithoutLogin - $results.Name | Should Be $userNameWithoutLogin + $results.Name | Should -Be $userNameWithoutLogin $results.DefaultSchema | Should -Be 'guest' $results.Login | Should -BeNullOrEmpty } @@ -74,6 +74,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $securePassword = ConvertTo-SecureString $password -AsPlainText -Force $null = New-DbaLogin -SqlInstance $script:instance2 -Login $loginName -Password $securePassword -Force $null = New-DbaDatabase -SqlInstance $script:instance2 -Name $dbs + $accessibleDbCount = (Get-DbaDatabase -SqlInstance $script:instance2 -ExcludeSystem -OnlyAccessible).count } AfterAll { $null = Remove-DbaDatabase -SqlInstance $script:instance2 -Database $dbs -Confirm:$false @@ -85,5 +86,11 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $results.Name | Should -Be $loginName, $loginName, $loginName $results.DefaultSchema | Should -Be dbo, dbo, dbo } + + It "Should add user to all user databases" { + $results = New-DbaDbUser -SqlInstance $script:instance2 -Login $loginName -Force -EnableException + $results.Count | Should -Be $accessibleDbCount + $results.Name | Get-Unique | Should -Be $loginName + } } } \ No newline at end of file diff --git a/tests/New-DbaReplCreationScriptOptions.Tests.ps1 b/tests/New-DbaReplCreationScriptOptions.Tests.ps1 new file mode 100644 index 0000000000..c7e06f9e13 --- /dev/null +++ b/tests/New-DbaReplCreationScriptOptions.Tests.ps1 @@ -0,0 +1,19 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'Options', 'NoDefaults' + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> \ No newline at end of file diff --git a/tests/New-DbaReplPublication.Tests.ps1 b/tests/New-DbaReplPublication.Tests.ps1 new file mode 100644 index 0000000000..7306059d09 --- /dev/null +++ b/tests/New-DbaReplPublication.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Name', 'Type', 'LogReaderAgentCredential', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> diff --git a/tests/New-DbaReplSubscription.Tests.ps1 b/tests/New-DbaReplSubscription.Tests.ps1 new file mode 100644 index 0000000000..64176e3048 --- /dev/null +++ b/tests/New-DbaReplSubscription.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'SubscriberSqlInstance', 'SubscriberSqlCredential', 'SubscriptionDatabase', 'PublicationName', 'SubscriptionSqlCredential', 'Type', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> diff --git a/tests/Remove-DbaReplArticle.Tests.ps1 b/tests/Remove-DbaReplArticle.Tests.ps1 new file mode 100644 index 0000000000..3df7559a0f --- /dev/null +++ b/tests/Remove-DbaReplArticle.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Publication', 'Schema', 'Name', 'InputObject', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> \ No newline at end of file diff --git a/tests/Remove-DbaReplPublication.Tests.ps1 b/tests/Remove-DbaReplPublication.Tests.ps1 new file mode 100644 index 0000000000..7914ec229d --- /dev/null +++ b/tests/Remove-DbaReplPublication.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'Name', 'InputObject', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> \ No newline at end of file diff --git a/tests/Remove-DbaReplSubscription.Tests.ps1 b/tests/Remove-DbaReplSubscription.Tests.ps1 new file mode 100644 index 0000000000..730d6870a6 --- /dev/null +++ b/tests/Remove-DbaReplSubscription.Tests.ps1 @@ -0,0 +1,20 @@ +$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "") +Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan +. "$PSScriptRoot\constants.ps1" + + +Add-ReplicationLibrary + +Describe "$CommandName Unit Tests" -Tag 'UnitTests' { + Context "Validate parameters" { + [object[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object {$_ -notin ('whatif', 'confirm')} + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'PublicationName', 'SubscriberSqlInstance', 'SubscriberSqlCredential', 'SubscriptionDatabase', 'EnableException' + $knownParameters += [System.Management.Automation.PSCmdlet]::CommonParameters + It "Should only contain our specific parameters" { + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object {$_}) -DifferenceObject $params).Count ) | Should Be 0 + } + } +} +<# + Integration tests for replication are in GitHub Actions and run from \tests\gh-actions-repl-*.ps1.ps1 +#> \ No newline at end of file diff --git a/tests/Test-DbaLastBackup.Tests.ps1 b/tests/Test-DbaLastBackup.Tests.ps1 index 498cba5c01..0731328b86 100644 --- a/tests/Test-DbaLastBackup.Tests.ps1 +++ b/tests/Test-DbaLastBackup.Tests.ps1 @@ -57,6 +57,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { It "Should return success" { $results.RestoreResult | Should Be "Success" $results.DbccResult | Should Be "Success" + $results.BackupDates | ForEach-Object { $_ | Should BeOfType DbaDateTime } } } @@ -84,7 +85,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $results.RestoreResult | Should Be "Success" } - It "Should tno contain a diff backup" { + It "Should not contain a diff backup" { ($results.BackupFiles | Where-Object { $_ -like '*diff*' }).count | Should -Be 0 } } diff --git a/tests/Test-DbaLoginPassword.Tests.ps1 b/tests/Test-DbaLoginPassword.Tests.ps1 index 4d9f88b96e..12769f6703 100644 --- a/tests/Test-DbaLoginPassword.Tests.ps1 +++ b/tests/Test-DbaLoginPassword.Tests.ps1 @@ -38,5 +38,9 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $results = Test-DbaLoginPassword -SqlInstance $script:instance1 -Login $weaksauce $results.SqlLogin | Should -Be $weaksauce } + It "handles passwords with quotes, see #9095" { + $results = Test-DbaLoginPassword -SqlInstance $script:instance1 -Login $weaksauce -Dictionary "&é`"'(-", "hello" + $results.SqlLogin | Should -Be $weaksauce + } } } \ No newline at end of file diff --git a/tests/Test-DbaRepLatency.Tests.ps1 b/tests/Test-DbaReplLatency.Tests.ps1 similarity index 100% rename from tests/Test-DbaRepLatency.Tests.ps1 rename to tests/Test-DbaReplLatency.Tests.ps1 diff --git a/tests/gh-actions-repl-1.ps1 b/tests/gh-actions-repl-1.ps1 new file mode 100644 index 0000000000..e925b6a295 --- /dev/null +++ b/tests/gh-actions-repl-1.ps1 @@ -0,0 +1,315 @@ +Describe "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $password = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force + $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "sqladmin", $password + + $PSDefaultParameterValues["*:SqlInstance"] = "mssql1" + $PSDefaultParameterValues["*:SqlCredential"] = $cred + $PSDefaultParameterValues["*:SubscriberSqlCredential"] = $cred + $PSDefaultParameterValues["*:Confirm"] = $false + $PSDefaultParameterValues["*:SharedPath"] = "/shared" + $PSDefaultParameterValues["*:WarningAction"] = "SilentlyContinue" + $global:ProgressPreference = "SilentlyContinue" + + Import-Module ./dbatools.psd1 -Force + + $null = New-DbaDatabase -Name ReplDb + $null = Invoke-DbaQuery -Database ReplDb -Query 'CREATE TABLE ReplicateMe ( id int identity (1,1) PRIMARY KEY, col1 varchar(10) ); CREATE TABLE ReplicateMeToo ( id int identity (1,1) PRIMARY KEY, col1 varchar(10) );' + } + + Describe "General commands" -Tag general { + + Context "Get-DbaReplServer works" { + + It "Doesn't throw errors" { + { Get-DbaReplServer -EnableException } | Should -Not -Throw + } + + It "Returns a ReplicationObject" { + (Get-DbaReplServer).GetType().BaseType | Should -Be "Microsoft.SqlServer.Replication.ReplicationObject" + } + + It "Gets a replication server" { + (Get-DbaReplServer).SqlInstance | Should -Be 'mssql1' + (Get-DbaReplServer).DistributorInstalled | Should -Not -BeNullOrEmpty + (Get-DbaReplServer).DistributorAvailable | Should -Not -BeNullOrEmpty + (Get-DbaReplServer).IsDistributor | Should -Not -BeNullOrEmpty + (Get-DbaReplServer).IsPublisher | Should -Not -BeNullOrEmpty + } + } + } + + Describe "Publishing\Distribution commands" -tag pub { + + Context "Get-DbaReplDistributor works" { + BeforeAll { + + # if distribution is enabled, disable it & enable it with defaults + if ((Get-DbaReplDistributor).IsDistributor) { + Disable-DbaReplDistributor + } + Enable-DbaReplDistributor + } + + It "gets a distributor without error" { + { Get-DbaReplDistributor -EnableException } | Should -Not -Throw + } + + It "gets a distributor" { + (Get-DbaReplDistributor).IsDistributor | Should -Be $true + } + + It "distribution database name is correct" { + (Get-DbaReplDistributor).DistributionDatabases.Name | Should -Be 'distribution' + } + + + } + + Context "Get-DbaReplPublisher works" { + BeforeAll { + # if distribution is disabled - enable it + if (-not (Get-DbaReplDistributor).IsDistributor) { + Enable-DbaReplDistributor + } + + # if publishing is disabled - enable it + if (-not (Get-DbaReplServer).IsPublisher) { + Enable-DbaReplPublishing -PublisherSqlLogin $cred -EnableException + } + } + + It "gets a publisher" { + (Get-DbaReplPublisher).PublisherType | Should -Be "MSSQLSERVER" + } + + + } + + Context "Enable-DbaReplDistributor works" { + BeforeAll { + # if distribution is enabled - disable it + if ((Get-DbaReplDistributor).IsDistributor) { + Disable-DbaReplDistributor + } + } + + It "distribution starts disabled" { + (Get-DbaReplDistributor).IsDistributor | Should -Be $false + } + + It "distribution is enabled" { + Enable-DbaReplDistributor + (Get-DbaReplDistributor).IsDistributor | Should -Be $true + } + } + + Context "Enable-DbaReplDistributor works with specified database name" { + BeforeAll { + # if distribution is enabled - disable it + if ((Get-DbaReplDistributor).IsDistributor) { + Disable-DbaReplDistributor + } + } + AfterAll { + if ((Get-DbaReplDistributor).IsDistributor) { + Disable-DbaReplDistributor + } + } + + It "distribution starts disabled" { + (Get-DbaReplDistributor).IsDistributor | Should -Be $false + } + + It "distribution is enabled with specific database" { + $distDb = ('distdb-{0}' -f (Get-Random)) + Enable-DbaReplDistributor -DistributionDatabase $distDb + (Get-DbaReplDistributor).DistributionDatabases.Name | Should -Be $distDb + } + } + + Context "Disable-DbaReplDistributor works" { + BeforeAll { + # if replication is disabled - enable it + if (-not (Get-DbaReplDistributor).IsDistributor) { + Enable-DbaReplDistributor + } + } + + It "distribution starts enabled" { + (Get-DbaReplDistributor).IsDistributor | Should -Be $true + } + + It "distribution is disabled" { + Disable-DbaReplDistributor + (Get-DbaReplDistributor).IsDistributor | Should -Be $false + } + } + + Context "Enable-DbaReplPublishing works" { + BeforeAll { + # if Publishing is enabled - disable it + if ((Get-DbaReplServer).IsPublisher) { + Disable-DbaReplPublishing + } + # if distribution is disabled - enable it + if (-not (Get-DbaReplDistributor).IsDistributor) { + Enable-DbaReplDistributor + } + } + + It "publishing starts disabled" { + (Get-DbaReplServer).IsPublisher | Should -Be $false + } + + It "publishing is enabled" { + { Enable-DbaReplPublishing -EnableException } | Should -Not -Throw + (Get-DbaReplServer).IsPublisher | Should -Be $true + } + } + + Context "Disable-DbaReplPublishing works" { + BeforeAll { + # if publishing is disabled - enable it + if (-not (Get-DbaReplServer).IsPublisher) { + write-output -message 'I should enable publishing' + Enable-DbaReplPublishing -EnableException + } + + # if distribution is disabled - enable it + if (-not (Get-DbaReplDistributor).IsDistributor) { + write-output -message 'I should enable distribution' + Enable-DbaReplDistributor -EnableException + } + } + + It "publishing starts enabled" { + (Get-DbaReplServer).IsPublisher | Should -Be $true + } + + It "publishing is disabled" { + { Disable-DbaReplPublishing -EnableException } | Should -Not -Throw + (Get-DbaReplServer).IsPublisher | Should -Be $false + } + } + } + + Describe "Publication commands" -tag pub { + + Context "Get-DbaReplPublication works" { + BeforeAll { + # if distribution is disabled - enable it + if (-not (Get-DbaReplDistributor).IsDistributor) { + Enable-DbaReplDistributor + } + + # if publishing is disabled - enable it + if (-not (Get-DbaReplServer).IsPublisher) { + Enable-DbaReplPublishing -PublisherSqlLogin $cred -EnableException + } + + # create a publication + $name = 'TestPub' + New-DbaReplPublication -Database ReplDb -Type Transactional -Name ('{0}-Trans' -f $Name) + New-DbaReplPublication -Database ReplDb -Type Merge -Name ('{0}-Merge' -f $Name) + $null = New-DbaDatabase -Name Test + New-DbaReplPublication -Database Test -Type Snapshot -Name ('{0}-Snapshot' -f $Name) + } + + It "gets all publications" { + Get-DbaReplPublication | Should -Not -BeNullOrEmpty + } + + It "gets publications for a specific database" { + Get-DbaReplPublication -Database ReplDb | Should -Not -BeNullOrEmpty + (Get-DbaRepPublication -Database ReplDb).DatabaseName | ForEach-Object { $_ | Should -Be 'ReplDb' } + } + + It "gets publications for a specific type" { + Get-DbaReplPublication -Type Transactional | Should -Not -BeNullOrEmpty + (Get-DbaRepPublication -Type Transactional).Type | ForEach-Object { $_ | Should -Be 'Transactional' } + } + + } + + Context "New-DbaReplPublication works" { + BeforeAll { + # if replication is disabled - enable it + if (-not (Get-DbaReplDistributor).IsDistributor) { + Enable-DbaReplDistributor + } + # if publishing is disabled - enable it + if (-not (Get-DbaReplServer).IsPublisher) { + Enable-DbaReplPublishing -PublisherSqlLogin $cred -EnableException + } + } + + It "New-DbaReplPublication creates a Transactional publication" { + $name = 'TestPub' + { New-DbaReplPublication -Database ReplDb -Type Transactional -Name $Name -EnableException } | Should -Not -Throw + (Get-DbaReplPublication -Name $Name) | Should -Not -BeNullOrEmpty + (Get-DbaReplPublication -Name $Name).DatabaseName | Should -Be 'ReplDb' + (Get-DbaReplPublication -Name $Name).Type | Should -Be 'Transactional' + } + It "New-DbaReplPublication creates a Snapshot publication" { + $name = 'Snappy' + { New-DbaReplPublication -Database ReplDb -Type Snapshot -Name $name -EnableException } | Should -Not -Throw + (Get-DbaReplPublication -Name $name) | Should -Not -BeNullOrEmpty + (Get-DbaReplPublication -Name $name).DatabaseName | Should -Be 'ReplDb' + (Get-DbaReplPublication -Name $name).Type | Should -Be 'Snapshot' + } + It "New-DbaReplPublication creates a Merge publication" { + $name = 'Mergey' + { New-DbaReplPublication -Database ReplDb -Type Merge -Name $name -EnableException } | Should -Not -Throw + (Get-DbaReplPublication -Name $name) | Should -Not -BeNullOrEmpty + (Get-DbaReplPublication -Name $name).DatabaseName | Should -Be 'ReplDb' + (Get-DbaReplPublication -Name $name).Type | Should -Be 'Merge' + } + } + + Context "Remove-DbaReplPublication works" { + BeforeAll { + # if replication is disabled - enable it + if (-not (Get-DbaReplDistributor).IsDistributor) { + Enable-DbaReplDistributor + } + # if publishing is disabled - enable it + if (-not (Get-DbaReplServer).IsPublisher) { + Enable-DbaReplPublishing -PublisherSqlLogin $cred -EnableException + } + $articleName = 'ReplicateMe' + + # we need some publications too + $pubName = 'TestTrans' + if (-not (Get-DbaReplPublication -Name $pubName -Type Transactional)) { + $null = New-DbaReplPublication -Database ReplDb -Type Transactional -Name $pubName + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubName -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubName -Name $articleName + } + + $pubName = 'TestSnap' + if (-not (Get-DbaReplPublication -Name $pubName -Type Snapshot)) { + $null = New-DbaReplPublication -Database ReplDb -Type Snapshot -Name $pubName + } + $pubName = 'TestMerge' + if (-not (Get-DbaReplPublication -Name $pubName -Type Merge)) { + $null = New-DbaReplPublication -Database ReplDb -Type Merge -Name $pubName + } + } + + It "Remove-DbaReplPublication removes a publication that has articles" { + $name = 'TestTrans' + { Remove-DbaReplPublication -Name $name -EnableException } | Should -Not -Throw + (Get-DbaReplPublication -Name $name) | Should -BeNullOrEmpty + } + + It "Remove-DbaReplPublication removes a publication that has no articles" { + $name = 'TestSnap' + { Remove-DbaReplPublication -Name $name -EnableException } | Should -Not -Throw + (Get-DbaReplPublication -Name $name) | Should -BeNullOrEmpty + } + + } + } +} diff --git a/tests/gh-actions-repl-2.ps1 b/tests/gh-actions-repl-2.ps1 new file mode 100644 index 0000000000..d80d258350 --- /dev/null +++ b/tests/gh-actions-repl-2.ps1 @@ -0,0 +1,337 @@ +Describe "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $password = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force + $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "sqladmin", $password + + $PSDefaultParameterValues["*:SqlInstance"] = "mssql1" + $PSDefaultParameterValues["*:SqlCredential"] = $cred + $PSDefaultParameterValues["*:SubscriberSqlCredential"] = $cred + $PSDefaultParameterValues["*:Confirm"] = $false + $PSDefaultParameterValues["*:SharedPath"] = "/shared" + $PSDefaultParameterValues["*:WarningAction"] = "SilentlyContinue" + $global:ProgressPreference = "SilentlyContinue" + + Import-Module ./dbatools.psd1 -Force + + $null = New-DbaDatabase -Name ReplDb + $null = Invoke-DbaQuery -Database ReplDb -Query 'CREATE TABLE ReplicateMe ( id int identity (1,1) PRIMARY KEY, col1 varchar(10) ); CREATE TABLE ReplicateMeToo ( id int identity (1,1) PRIMARY KEY, col1 varchar(10) );' + } + + Describe "Article commands" -tag art { + BeforeAll { + # if replication is disabled - enable it + if (-not (Get-DbaReplDistributor).IsDistributor) { + Enable-DbaReplDistributor + } + # if publishing is disabled - enable it + if (-not (Get-DbaReplServer).IsPublisher) { + Enable-DbaReplPublishing -PublisherSqlLogin $cred -EnableException + } + # we need some publications too + $name = 'TestTrans' + if (-not (Get-DbaReplPublication -Name $name -Type Transactional )) { + $null = New-DbaReplPublication -Database ReplDb -Type Transactional -Name $Name + } + $name = 'TestSnap' + if (-not (Get-DbaReplPublication -Name $name -Type Snapshot)) { + $null = New-DbaReplPublication -Database ReplDb -Type Snapshot -Name $Name + } + $name = 'TestMerge' + if (-not (Get-DbaReplPublication -Name $name -Type Merge)) { + $null = New-DbaReplPublication -Database ReplDb -Type Merge -Name $Name + } + $articleName = 'ReplicateMe' + $articleName2 = 'ReplicateMeToo' + } + + Context "New-DbaReplCreationScriptOptions works" { + It "New-DbaReplCreationScriptOptions creates a Microsoft.SqlServer.Replication.CreationScriptOptions" { + $options = New-DbaReplCreationScriptOptions + $options | Should -BeOfType Microsoft.SqlServer.Replication.CreationScriptOptions + } + It "Microsoft.SqlServer.Replication.CreationScriptOptions should include the 11 defaults by default" { + ((New-DbaReplCreationScriptOptions).ToString().Split(',').Trim() | Measure-Object).Count | Should -Be 11 + } + It "Microsoft.SqlServer.Replication.CreationScriptOptions should include ClusteredIndexes" { + ((New-DbaReplCreationScriptOptions).ToString().Split(',').Trim() | Should -Contain 'ClusteredIndexes') + } + It "Microsoft.SqlServer.Replication.CreationScriptOptions with option of NonClusteredIndexes should add NonClusteredIndexes" { + ((New-DbaReplCreationScriptOptions -Option NonClusteredIndexes).ToString().Split(',').Trim() | Measure-Object).Count | Should -Be 12 + ((New-DbaReplCreationScriptOptions -Option NonClusteredIndexes).ToString().Split(',').Trim() | Should -Contain 'NonClusteredIndexes') + } + + It "NoDefaults should mean Microsoft.SqlServer.Replication.CreationScriptOptions only contains DisableScripting" { + ((New-DbaReplCreationScriptOptions -NoDefaults).ToString().Split(',').Trim() | Measure-Object).Count | Should -Be 1 + ((New-DbaReplCreationScriptOptions -NoDefaults).ToString().Split(',').Trim() | Should -Contain 'DisableScripting') + } + It "NoDefaults plus option of NonClusteredIndexes should mean Microsoft.SqlServer.Replication.CreationScriptOptions only contains NonClusteredIndexes" { + ((New-DbaReplCreationScriptOptions -NoDefaults -Option NonClusteredIndexes).ToString().Split(',').Trim() | Measure-Object).Count | Should -Be 1 + ((New-DbaReplCreationScriptOptions -NoDefaults -Option NonClusteredIndexes).ToString().Split(',').Trim() | Should -Contain 'NonClusteredIndexes') + } + } + + Context "Add-DbaReplArticle works" { + BeforeAll { + # remove all articles + $null = Get-DbaReplArticle -Database ReplDb | Remove-DbaReplArticle -Confirm:$false + } + + It "Add-DbaReplArticle adds an article to a Transactional publication" { + $pubName = 'TestTrans' + { Add-DbaReplArticle -Database ReplDb -Name $articleName -Publication $pubName -EnableException } | Should -not -throw + $art = Get-DbaReplArticle -Database ReplDb -Name $articleName -Publication $pubName + $art | Should -Not -BeNullOrEmpty + $art.PublicationName | Should -Be $pubName + $art.Name | Should -Be $articleName + } + + It "Add-DbaReplArticle adds an article to a Snapshot publication and specifies create script options" { + $pubname = 'TestTrans' + $cso = New-DbaReplCreationScriptOptions -Options NonClusteredIndexes, Statistics + { Add-DbaReplArticle -Database ReplDb -Name $articleName2 -Publication $pubname -CreationScriptOptions $cso -EnableException } | Should -not -throw + $art = Get-DbaReplArticle -Database ReplDb -Name $articleName2 -Publication $pubName + $art | Should -Not -BeNullOrEmpty + $art.PublicationName | Should -Be $pubName + $art.Name | Should -Be $articleName2 + } + + It "Add-DbaReplArticle adds an article to a Snapshot publication" { + $pubname = 'TestSnap' + { Add-DbaReplArticle -Database ReplDb -Name $articleName -Publication $pubname -EnableException } | Should -not -throw + $art = Get-DbaReplArticle -Database ReplDb -Name $articleName -Publication $pubName + $art | Should -Not -BeNullOrEmpty + $art.PublicationName | Should -Be $pubName + $art.Name | Should -Be $articleName + } + + It "Add-DbaReplArticle adds an article to a Snapshot publication with a filter" { + $pubName = 'TestSnap' + { Add-DbaReplArticle -Database ReplDb -Name $articleName2 -Publication $pubName -Filter "col1 = 'test'" -EnableException } | Should -not -throw + $art = Get-DbaReplArticle -Database ReplDb -Name $articleName2 -Publication $pubName + $art | Should -Not -BeNullOrEmpty + $art.PublicationName | Should -Be $pubName + $art.Name | Should -Be $articleName2 + $art.FilterClause | Should -Be "col1 = 'test'" + } + + It "Add-DbaReplArticle adds an article to a Merge publication" { + $pubname = 'TestMerge' + { Add-DbaReplArticle -Database ReplDb -Name $articleName -Publication $pubname -EnableException } | Should -not -throw + $art = Get-DbaReplArticle -Database ReplDb -Name $articleName -Publication $pubName + $art | Should -Not -BeNullOrEmpty + $art.PublicationName | Should -Be $pubName + $art.Name | Should -Be $articleName + } + } + + Context "Get-DbaReplArticle works" { + BeforeAll { + # we need some articles too get + $articleName = 'ReplicateMe' + $articleName2 = 'ReplicateMeToo' + + # we need some publications too + $pubName = 'TestTrans' + if (-not (Get-DbaReplPublication -Name $pubName -Type Transactional)) { + $null = New-DbaReplPublication -Database ReplDb -Type Transactional -Name $pubName + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubName -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubName -Name $articleName + } + + $pubName = 'TestSnap' + if (-not (Get-DbaReplPublication -Name $pubName -Type Snapshot)) { + $null = New-DbaReplPublication -Database ReplDb -Type Snapshot -Name $pubName + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName2 + } + + $pubName = 'TestMerge' + if (-not (Get-DbaReplPublication -Name $pubName -Type Merge)) { + $null = New-DbaReplPublication -Database ReplDb -Type Merge -Name $pubName + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName + } + } + + It "Get-DbaReplArticle gets all the articles from a server" { + $getArt = Get-DbaReplArticle + $getArt | Should -Not -BeNullOrEmpty + $getArt | ForEach-Object { $_.SqlInstance.name | Should -Be 'mssql1' } + } + + It "Get-DbaReplArticle gets all the articles from a particular database on a server" { + $getArt = Get-DbaReplArticle -Database ReplDb + $getArt | Should -Not -BeNullOrEmpty + $getArt | ForEach-Object { $_.SqlInstance.Name | Should -Be 'mssql1' } + $getArt | ForEach-Object { $_.DatabaseName | Should -Be 'ReplDb' } + } + + It "Get-DbaReplArticle gets all the articles from a specific publication" { + $pubName = 'TestSnap' + $arts = $articleName, $articleName2 + + $getArt = Get-DbaReplArticle -Database ReplDb -Publication $pubName + $getArt.Count | Should -Be 2 + $getArt.Name | Should -Be $arts + $getArt | Foreach-Object { $_.PublicationName | Should -Be $pubName } + } + + It "Get-DbaReplArticle gets a certain article from a specific publication" { + $pubName = 'TestTrans' + + $getArt = Get-DbaReplArticle -Database ReplDb -Publication $pubName -Name $articleName + $getArt.Count | Should -Be 1 + $getArt.Name | Should -Be $ArticleName + $getArt.PublicationName | Should -Be $pubName + } + } + + Context "Remove-DbaReplArticle works" { + BeforeAll { + # we need some articles too remove + $articleName = 'ReplicateMe' + + # we need some publications with articles too + $pubname = 'TestTrans' + if (-not (Get-DbaReplPublication -Name $pubname -Type Transactional)) { + $null = New-DbaReplPublication -Database ReplDb -Type Transactional -Name $pubname + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName + } + + $pubname = 'TestSnap' + if (-not (Get-DbaReplPublication -Name $pubname -Type Snapshot)) { + $null = New-DbaReplPublication -Database ReplDb -Type Snapshot -Name $pubname + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName + } + + $pubname = 'TestMerge' + if (-not (Get-DbaReplPublication -Name $pubname -Type Merge)) { + $null = New-DbaReplPublication -Database ReplDb -Type Merge -Name $pubname + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName + } + + } + + It "Remove-DbaReplArticle removes an article from a Transactional publication" { + $pubname = 'TestTrans' + $Name = "ReplicateMe" + $rm = Remove-DbaReplArticle -Database ReplDb -Publication $pubname -Name $Name + $rm.IsRemoved | Should -Be $true + $rm.Status | Should -Be 'Removed' + $articleName = Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $Name + $articleName | Should -BeNullOrEmpty + } + + It "Remove-DbaReplArticle removes an article from a Snapshot publication" { + $pubname = 'TestSnap' + $Name = "ReplicateMe" + $rm = Remove-DbaReplArticle -Database ReplDb -Publication $pubname -Name $Name + $rm.IsRemoved | Should -Be $true + $rm.Status | Should -Be 'Removed' + $articleName = Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $Name + $articleName | Should -BeNullOrEmpty + } + + It "Remove-DbaReplArticle removes an article from a Merge publication" { + $pubname = 'TestMerge' + $Name = "ReplicateMe" + $rm = Remove-DbaReplArticle -Database ReplDb -Publication $pubname -Name $Name + $rm.IsRemoved | Should -Be $true + $rm.Status | Should -Be 'Removed' + $articleName = Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $Name + $articleName | Should -BeNullOrEmpty + } + } + + + } + + Describe "Article Column commands" -tag art { + BeforeAll { + # if replication is disabled - enable it + if (-not (Get-DbaReplDistributor).IsDistributor) { + Enable-DbaReplDistributor + } + # if publishing is disabled - enable it + if (-not (Get-DbaReplServer).IsPublisher) { + Enable-DbaReplPublishing -PublisherSqlLogin $cred -EnableException + } + $articleName = 'ReplicateMe' + + # we need some publications with articles too + $pubname = 'TestTrans' + if (-not (Get-DbaReplPublication -Name $pubname -Type Transactional)) { + $null = New-DbaReplPublication -Database ReplDb -Type Transactional -Name $pubname + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName + } + + $pubname = 'TestSnap' + if (-not (Get-DbaReplPublication -Name $pubname -Type Snapshot)) { + $null = New-DbaReplPublication -Database ReplDb -Type Snapshot -Name $pubname + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName + } + + $pubname = 'TestMerge' + if (-not (Get-DbaReplPublication -Name $pubname -Type Merge)) { + $null = New-DbaReplPublication -Database ReplDb -Type Merge -Name $pubname + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName + } + } + + Context "Get-DbaReplArticleColumn works" { + It "Gets all column information for a server" { + $cols = Get-DbaReplArticleColumn + $cols | Should -Not -BeNullOrEmpty + $cols.SqlInstance | ForEach-Object { $_.Name | Should -Be 'mssql1' } + } + + It "Gets all column information for specific database on a server" { + $cols = Get-DbaReplArticleColumn -Database ReplDb + $cols | Should -Not -BeNullOrEmpty + $cols.SqlInstance | ForEach-Object { $_.Name | Should -Be 'mssql1' } + $cols.DatabaseName | ForEach-Object { $_ | Should -Be 'ReplDb' } + } + + It "Gets all column information for specific publication on a server" { + $pubname = 'TestTrans' + $cols = Get-DbaReplArticleColumn -Publication $pubname + $cols | Should -Not -BeNullOrEmpty + $cols.SqlInstance | ForEach-Object { $_.Name | Should -Be 'mssql1' } + $cols.PublicationName | ForEach-Object { $_ | Should -Be $pubname } + } + + It "Gets all column information for specific article on a server" { + $pubname = 'TestTrans' + $cols = Get-DbaReplArticleColumn -Publication $pubname -Article $articleName + $cols | Should -Not -BeNullOrEmpty + $cols.SqlInstance | ForEach-Object { $_.Name | Should -Be 'mssql1' } + $cols.ArticleName | ForEach-Object { $_ | Should -Be $articleName } + } + + It "Gets all column information for specific column on a server" { + $pubname = 'TestTrans' + $cols = Get-DbaReplArticleColumn -Publication $pubname -Column 'col1' + $cols | Should -Not -BeNullOrEmpty + $cols.SqlInstance | ForEach-Object { $_.Name | Should -Be 'mssql1' } + $cols.ColumnName | ForEach-Object { $_ | Should -Be 'col1' } + } + } + } + +} diff --git a/tests/gh-actions-repl-3.ps1 b/tests/gh-actions-repl-3.ps1 new file mode 100644 index 0000000000..870d55485c --- /dev/null +++ b/tests/gh-actions-repl-3.ps1 @@ -0,0 +1,282 @@ +Describe "Integration Tests" -Tag "IntegrationTests" { + BeforeAll { + $password = ConvertTo-SecureString "dbatools.IO" -AsPlainText -Force + $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "sqladmin", $password + + $PSDefaultParameterValues["*:SqlInstance"] = "mssql1" + $PSDefaultParameterValues["*:SqlCredential"] = $cred + $PSDefaultParameterValues["*:SubscriberSqlCredential"] = $cred + $PSDefaultParameterValues["*:Confirm"] = $false + $PSDefaultParameterValues["*:SharedPath"] = "/shared" + $PSDefaultParameterValues["*:WarningAction"] = "SilentlyContinue" + $global:ProgressPreference = "SilentlyContinue" + + Import-Module ./dbatools.psd1 -Force + + $null = New-DbaDatabase -Name ReplDb + $null = Invoke-DbaQuery -Database ReplDb -Query 'CREATE TABLE ReplicateMe ( id int identity (1,1) PRIMARY KEY, col1 varchar(10) ); CREATE TABLE ReplicateMeToo ( id int identity (1,1) PRIMARY KEY, col1 varchar(10) );' + } + + + Describe "Subscription commands" -tag sub { + BeforeAll { + # if replication is disabled - enable it + #if (-not (Get-DbaReplDistributor).IsDistributor) { + # Enable-DbaReplDistributor + #} + ## if publishing is disabled - enable it + #if (-not (Get-DbaReplServer).IsPublisher) { + # Enable-DbaReplPublishing -PublisherSqlLogin $cred -EnableException + #} + #$articleName = 'ReplicateMe' + + <# + # we need some publications with articles too + $pubname = 'TestTrans' + if (-not (Get-DbaReplPublication -Name $pubname -Type Transactional)) { + $null = New-DbaReplPublication -Database ReplDb -Type Transactional -Name $pubname + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName + } + + $pubname = 'TestSnap' + if (-not (Get-DbaReplPublication -Name $pubname -Type Snapshot)) { + $null = New-DbaReplPublication -Database ReplDb -Type Snapshot -Name $pubname + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName + } + + $pubname = 'TestMerge' + if (-not (Get-DbaReplPublication -Name $pubname -Type Merge)) { + $null = New-DbaReplPublication -Database ReplDb -Type Merge -Name $pubname + } + #> + } + + Context "New-DbaReplSubscription works" -skip { + BeforeAll { + if (Get-DbaReplSubscription -SqlInstance mssql1 -PublicationName TestTrans) { + (Get-DbaReplSubscription -SqlInstance mssql1 -PublicationName TestTrans).foreach{ + Remove-DbaReplSubscription -SqlInstance $psitem.SqlInstance -SubscriptionDatabase $psitem.SubscriptionDBName -SubscriberSqlInstance $psitem.SubscriberName -Database $psitem.DatabaseName -PublicationName $psitem.PublicationName -Confirm:$false -EnableException + } + } + if (Get-DbaReplSubscription -SqlInstance mssql1 -PublicationName TestSnap) { + (Get-DbaReplSubscription -SqlInstance mssql1 -PublicationName TestSnap).foreach{ + Remove-DbaReplSubscription -SqlInstance $psitem.SqlInstance -SubscriptionDatabase $psitem.SubscriptionDBName -SubscriberSqlInstance $psitem.SubscriberName -Database $psitem.DatabaseName -PublicationName $psitem.PublicationName -Confirm:$false -EnableException + } + } + Get-DbaReplArticle -Publication TestSnap | Remove-DbaReplArticle -Confirm:$false + } + It "Adds a subscription" { + $pubName = 'TestTrans' + { New-DbaReplSubscription -SqlInstance mssql1 -Database ReplDb -SubscriberSqlInstance mssql2 -SubscriptionDatabase ReplDbTrans -PublicationName $pubName -Type Push -EnableException } | Should -Not -Throw + + $sub = Get-DbaReplSubscription -SqlInstance mssql1 -PublicationName $pubname + $sub | Should -Not -BeNullOrEmpty + $sub.SqlInstance | ForEach-Object { $_ | Should -Be 'mssql1' } + $sub.SubscriberName | ForEach-Object { $_ | Should -Be 'mssql2' } + $sub.PublicationName | ForEach-Object { $_ | Should -Be $pubname } + $sub.SubscriptionType | ForEach-Object { $_ | Should -Be 'Push' } + } + + It "Adds a pull subscription" { + #TODO: Fix pull subscriptions in New-DbaReplSubscription command + $pubName = 'TestMerge' + { New-DbaReplSubscription -SqlInstance mssql1 -Database ReplDb -SubscriberSqlInstance mssql2 -SubscriptionDatabase ReplDbSnap -PublicationName $pubName -Type Pull -EnableException } | Should -Not -Throw + + $sub = Get-DbaReplSubscription -SqlInstance mssql1 -PublicationName $pubname + $sub | Should -Not -BeNullOrEmpty + $sub.SqlInstance | ForEach-Object { $_ | Should -Be 'mssql1' } + $sub.SubscriberName | ForEach-Object { $_ | Should -Be 'mssql2' } + $sub.PublicationName | ForEach-Object { $_ | Should -Be $pubname } + $sub.SubscriptionType | ForEach-Object { $_ | Should -Be 'Pull' } + } + + It "Throws an error if there are no articles in the publication" { + $pubName = 'TestSnap' + { New-DbaReplSubscription -SqlInstance mssql1 -Database ReplDb -SubscriberSqlInstance mssql2 -SubscriptionDatabase ReplDb -PublicationName $pubName -Type Pull -EnableException } | Should -Throw + } + } + + Context "Remove-DbaReplSubscription works" -skip { + BeforeEach { + $pubName = 'TestTrans' + if (-not (Get-DbaReplSubscription -SqlInstance mssql1 -Database ReplDb -SubscriptionDatabase ReplDb -PublicationName $pubname -Type Push | Where-Object SubscriberName -eq mssql2)) { + New-DbaReplSubscription -SqlInstance mssql1 -Database ReplDb -SubscriberSqlInstance mssql2 -SubscriptionDatabase ReplDb -PublicationName $pubname -Type Push + } + } + It "Removes a push subscription" { + Get-DbaReplSubscription -SqlInstance mssql1 -Database ReplDb -SubscriptionDatabase ReplDb -PublicationName $pubname -Type Push | Should -Not -BeNullOrEmpty + { Remove-DbaReplSubscription -SqlInstance mssql1 -SubscriptionDatabase ReplDb -SubscriberSqlInstance mssql2 -Database ReplDb -PublicationName $pubname -EnableException } | Should -Not -Throw + Get-DbaReplSubscription -SqlInstance mssql1 -Database ReplDb -SubscriptionDatabase ReplDb -PublicationName $pubname -Type Push | Where-Object SubscriberName -eq mssql2 | Should -BeNullOrEmpty + } + It "Removes a pull subscription" -skip { + #TODO: Fix pull subscriptions in New-DbaReplSubscription command + Get-DbaReplSubscription -SqlInstance mssql1 -Database ReplDb -SubscriptionDatabase ReplDb -PublicationName $pubname -Type Pull | Should -Not -BeNullOrEmpty + { Remove-DbaReplSubscription -SqlInstance mssql1 -SubscriptionDatabase ReplDb -SubscriberSqlInstance mssql2 -Database ReplDb -PublicationName $pubname -EnableException } | Should -Not -Throw + Get-DbaReplSubscription -SqlInstance mssql1 -Database ReplDb -SubscriptionDatabase ReplDb -PublicationName $pubname -Type Pull | Where-Object SubscriberName -eq mssql2 | Should -BeNullOrEmpty + } + } + + + Context "Get-DbaReplSubscription works" { + BeforeAll { + $pubname = 'TestTrans' + $articleName = 'ReplicateMe' + if (-not (Get-DbaReplPublication -Name $pubname -Type Transactional)) { + $null = New-DbaReplPublication -Database ReplDb -Type Transactional -Name $pubname + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName + } + if (-not (Get-DbaReplSubscription -PublicationName $pubname -Type Push | Where-Object SubscriberName -eq mssql2)) { + New-DbaReplSubscription -SqlInstance mssql1 -Database ReplDb -SubscriberSqlInstance mssql2 -SubscriptionDatabase ReplDb -PublicationName $pubname -Type Push -enableException + } + + $pubName = 'TestSnap' + if (-not (Get-DbaReplPublication -Name $pubname -Type Snapshot)) { + $null = New-DbaReplPublication -Database ReplDb -Type Snapshot -Name $pubname + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName + } + if (-not (Get-DbaReplSubscription -PublicationName $pubname -Type Push | Where-Object SubscriberName -eq mssql2)) { + New-DbaReplSubscription -SqlInstance mssql1 -Database ReplDb -SubscriberSqlInstance mssql2 -SubscriptionDatabase ReplDb -PublicationName $pubname -Type Push -enableException + } + } + + It "Gets subscriptions" { + $sub = Get-DbaReplSubscription -SqlInstance mssql1 + $sub | Should -Not -BeNullOrEmpty + $sub.SqlInstance | ForEach-Object { $_ | Should -Be 'mssql1' } + } + + It "Gets subscriptions for a particular database" { + $sub = Get-DbaReplSubscription -SqlInstance mssql1 -Database ReplDb + $sub | Should -Not -BeNullOrEmpty + $sub.DatabaseName | ForEach-Object { $_ | Should -Be 'ReplDb' } + } + + It "Gets subscriptions by publication name" { + $sub = Get-DbaReplSubscription -SqlInstance mssql1 -PublicationName TestTrans + $sub | Should -Not -BeNullOrEmpty + $sub.PublicationName | ForEach-Object { $_ | Should -Be 'TestTrans' } + } + + It "Gets subscriptions by type" { + $sub = Get-DbaReplSubscription -SqlInstance mssql1 -Type Push + $sub | Should -Not -BeNullOrEmpty + $sub.SubscriptionType | ForEach-Object { $_ | Should -Be 'Push' } + + $sub = Get-DbaReplSubscription -SqlInstance mssql1 -Type Pull + if($sub) { + $sub.SubscriptionType | ForEach-Object { $_ | Should -Be 'Pull' } + } + } + + It "Gets subscriptions by subscriber name" { + $sub = Get-DbaReplSubscription -SqlInstance mssql1 -SubscriberName mssql2 + $sub | Should -Not -BeNullOrEmpty + $sub.SubscriberName | ForEach-Object { $_ | Should -Be 'mssql2' } + } + + It "Gets subscriptions by subscription database name" { + $sub = Get-DbaReplSubscription -SqlInstance mssql1 -SubscriptionDatabase ReplDbTrans + $sub | Should -Not -BeNullOrEmpty + $sub.SubscriptionDBName | ForEach-Object { $_ | Should -Be 'ReplDbTrans' } + } + } + } + + Describe "Piping" -tag pipe { + BeforeAll { + # if replication is disabled - enable it + if (-not (Get-DbaReplDistributor).IsDistributor) { + Enable-DbaReplDistributor + } + # if publishing is disabled - enable it + if (-not (Get-DbaReplServer).IsPublisher) { + Enable-DbaReplPublishing -PublisherSqlLogin $cred -EnableException + } + + # we need some articles too get + $articleName = 'ReplicateMe' + $articleName2 = 'ReplicateMeToo' + + # we need some publications too + $pubName = 'TestTrans' + if (-not (Get-DbaReplPublication -Name $pubName -Type Transactional)) { + $null = New-DbaReplPublication -Database ReplDb -Type Transactional -Name $pubName -EnableException + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubName -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubName -Name $articleName -EnableException + } + + $pubName = 'TestSnap' + if (-not (Get-DbaReplPublication -Name $pubName -Type Snapshot)) { + $null = New-DbaReplPublication -Database ReplDb -Type Snapshot -Name $pubName -EnableException + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName -EnableException + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName2 -EnableException + } + + $pubName = 'TestMerge' + if (-not (Get-DbaReplPublication -Name $pubName -Type Merge)) { + $null = New-DbaReplPublication -Database ReplDb -Type Merge -Name $pubName -EnableException + } + if (-not (Get-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName)) { + $null = Add-DbaReplArticle -Database ReplDb -Publication $pubname -Name $articleName -EnableException + } + # piping doesn't work well if there are PSDefaultParameterValues set + $PSDefaultParameterValues = $null + } + + Context "Get-DbaReplPublisher works with piping" { + It "gets a publisher using piping" { + (Connect-DbaInstance -SqlInstance 'mssql1' -SqlCredential $cred | Get-DbaReplPublisher).PublisherType | Should -Be "MSSQLSERVER" + } + } + + Context "Get-DbaReplPublication works with piping" { + It "works with piping" { + Connect-DbaInstance -SqlInstance 'mssql1' -SqlCredential $cred | Get-DbaReplPublication | Should -Not -BeNullOrEmpty + } + } + + Context "Get-DbaReplDistributor works with piping" { + It "can pipe a sql server object to it" { + Connect-DbaInstance -SqlInstance 'mssql1' -SqlCredential $cred | Get-DbaReplDistributor | Should -Not -BeNullOrEmpty + } + } + + Context "Get-DbaReplArticle works with piping" { + It "Piping from Connect-DbaInstance to works" { + Connect-DbaInstance -SqlInstance 'mssql1' -SqlCredential $cred -Database ReplDb | Get-DbaReplArticle | Should -Not -BeNullOrEmpty + } + } + + Context "Remove-DbaReplArticle works with piping" { + It "Remove-DbaReplArticle removes an article from a Transactional publication" { + $pubName = 'TestTrans' + $Name = "ReplicateMe" + + $rm = Get-DbaReplArticle -SqlInstance 'mssql1' -SqlCredential $cred -Database ReplDb -Publication $pubName -Name $Name | Remove-DbaReplArticle -Confirm:$false + $rm.IsRemoved | ForEach-Object { $_ | Should -Be $true } + $rm.Status | ForEach-Object { $_ | Should -Be 'Removed' } + $articleName = Get-DbaReplArticle -SqlInstance 'mssql1' -SqlCredential $cred -Database ReplDb -Publication $pubName -Name $Name + $articleName | Should -BeNullOrEmpty + } + } + + Context "Remove-DbaReplPublication works with piping" { + It "Remove-DbaReplPublication removes a publication using piping" { + $name = 'TestMerge' + { Get-DbaReplPublication -SqlInstance 'mssql1' -SqlCredential $cred -Name $name -EnableException | Remove-DbaReplPublication -Confirm:$false -EnableException } | Should -Not -Throw + (Get-DbaReplPublication -SqlInstance 'mssql1' -SqlCredential $cred -Name $name -EnableException) | Should -BeNullOrEmpty + } + } + } +} diff --git a/tests/gh-actions.ps1 b/tests/gh-actions.ps1 index 9adbf0203f..8c7346dfc5 100644 --- a/tests/gh-actions.ps1 +++ b/tests/gh-actions.ps1 @@ -256,7 +256,7 @@ exec sp_addrolemember 'userrole','bob'; $results.Status | Should -Be "Successful" } - It "connects to Azure" { + It "connects to Azure" -Skip { $PSDefaultParameterValues.Clear() $securestring = ConvertTo-SecureString $env:CLIENTSECRET -AsPlainText -Force $azurecred = New-Object PSCredential -ArgumentList $env:CLIENTID, $securestring @@ -264,7 +264,7 @@ exec sp_addrolemember 'userrole','bob'; Connect-DbaInstance -SqlInstance "Server=dbatoolstest.database.windows.net; Authentication=Active Directory Service Principal; Database=test; User Id=$env:CLIENTID; Password=$env:CLIENTSECRET;" | Select-Object -ExpandProperty ComputerName | Should -Be "dbatoolstest.database.windows.net" } - It "gets a database from Azure" { + It "gets a database from Azure" -Skip { $PSDefaultParameterValues.Clear() $securestring = ConvertTo-SecureString $env:CLIENTSECRET -AsPlainText -Force $azurecred = New-Object PSCredential -ArgumentList $env:CLIENTID, $securestring @@ -272,7 +272,7 @@ exec sp_addrolemember 'userrole','bob'; (Get-DbaDatabase -SqlInstance $server -Database test).Name | Should -Be "test" } - It "tests Get-DbaLastGoodCheckDb against Azure" { + It "tests Get-DbaLastGoodCheckDb against Azure" -Skip { $PSDefaultParameterValues.Clear() $securestring = ConvertTo-SecureString $env:CLIENTSECRET -AsPlainText -Force $azurecred = New-Object PSCredential -ArgumentList $env:CLIENTID, $securestring @@ -297,4 +297,4 @@ Need to add tests for CSV 'Remove-DbaDatabaseSafely', 'Test-DbaManagementObject', 'Export-DbaDacPackage' -#> \ No newline at end of file +#> diff --git a/tests/gh-macactions.ps1 b/tests/gh-macactions.ps1 index 34f1adc53f..f3551d4fab 100644 --- a/tests/gh-macactions.ps1 +++ b/tests/gh-macactions.ps1 @@ -36,7 +36,7 @@ Describe "Integration Tests" -Tag "IntegrationTests" { $null = Remove-DbaDatabase -Database $db.Name } - It "connects to Azure" { + It "connects to Azure" -Skip { $PSDefaultParameterValues.Clear() $securestring = ConvertTo-SecureString $env:CLIENTSECRET -AsPlainText -Force $azurecred = New-Object PSCredential -ArgumentList $env:CLIENTID, $securestring @@ -44,7 +44,7 @@ Describe "Integration Tests" -Tag "IntegrationTests" { Connect-DbaInstance -SqlInstance "Server=dbatoolstest.database.windows.net; Authentication=Active Directory Service Principal; Database=test; User Id=$env:CLIENTID; Password=$env:CLIENTSECRET;" | Select-Object -ExpandProperty ComputerName | Should -Be "dbatoolstest.database.windows.net" } - It "gets a database from Azure" { + It "gets a database from Azure" -Skip { $PSDefaultParameterValues.Clear() $securestring = ConvertTo-SecureString $env:CLIENTSECRET -AsPlainText -Force $azurecred = New-Object PSCredential -ArgumentList $env:CLIENTID, $securestring diff --git a/tests/gh-winactions.ps1 b/tests/gh-winactions.ps1 index d6c103f984..6b6e3a31fe 100644 --- a/tests/gh-winactions.ps1 +++ b/tests/gh-winactions.ps1 @@ -33,7 +33,7 @@ Describe "Integration Tests" -Tag "IntegrationTests" { $null = Remove-DbaDatabase -Database $db.Name } - It "connects to Azure using tenant and client id + client secret" { + It "connects to Azure using tenant and client id + client secret" -Skip { $PSDefaultParameterValues.Clear() $securestring = ConvertTo-SecureString $env:CLIENTSECRET -AsPlainText -Force $azurecred = New-Object PSCredential -ArgumentList $env:CLIENTID, $securestring @@ -41,7 +41,7 @@ Describe "Integration Tests" -Tag "IntegrationTests" { } - It "connects to Azure using a query string" { + It "connects to Azure using a query string" -Skip { # this doesn't work on github, it throws # Method not found: 'Microsoft.Identity.Client.AcquireTokenByUsernamePasswordParameterBuilder' if ($PSVersionTable.PSEdition -eq "Core") { @@ -53,7 +53,7 @@ Describe "Integration Tests" -Tag "IntegrationTests" { } } - It "gets a database from Azure" { + It "gets a database from Azure" -Skip { $PSDefaultParameterValues.Clear() $securestring = ConvertTo-SecureString $env:CLIENTSECRET -AsPlainText -Force $azurecred = New-Object PSCredential -ArgumentList $env:CLIENTID, $securestring diff --git a/tests/pester.groups.ps1 b/tests/pester.groups.ps1 index a2fb1f3def..8bdf3fb0b2 100644 --- a/tests/pester.groups.ps1 +++ b/tests/pester.groups.ps1 @@ -69,7 +69,8 @@ $TestsRunGroups = @{ # just fails too often 'Remove-DbaDbTableData', 'Test-DbaMaxDop', - 'Test-DbaOptimizeForAdHoc' + 'Test-DbaOptimizeForAdHoc', + 'New-DbaDbSnapshot' ) # do not run everywhere "disabled" = @()