diff --git a/bin/dbatools-index.json b/bin/dbatools-index.json index 36396eb3303e..9cfb0765533f 100644 Binary files a/bin/dbatools-index.json and b/bin/dbatools-index.json differ diff --git a/bin/type-extensions.ps1 b/bin/type-extensions.ps1 deleted file mode 100644 index 56bf0fb398dc..000000000000 --- a/bin/type-extensions.ps1 +++ /dev/null @@ -1,45 +0,0 @@ -# Only update on first import -if (-not ([Dataplat.Dbatools.dbaSystem.SystemHost]::ModuleImported)) { - # Implement query accelerator for the server object - Update-TypeData -TypeName Microsoft.SqlServer.Management.Smo.Server -MemberName Query -MemberType ScriptMethod -Value { - param ( - $Query, - - $Database = "master", - - $AllTables = $false - ) - - if ($AllTables) { ($this.Databases[$Database].ExecuteWithResults($Query)).Tables } - else { ($this.Databases[$Database].ExecuteWithResults($Query)).Tables[0] } - } -ErrorAction Ignore - - Update-TypeData -TypeName Microsoft.SqlServer.Management.Smo.Server -MemberName Invoke -MemberType ScriptMethod -Value { - param ( - $Command, - - $Database = "master" - ) - - $this.Databases[$Database].ExecuteNonQuery($Command) - } -ErrorAction Ignore - - Update-TypeData -TypeName Microsoft.SqlServer.Management.Smo.Database -MemberName Query -MemberType ScriptMethod -Value { - param ( - $Query, - - $AllTables = $false - ) - - if ($AllTables) { ($this.ExecuteWithResults($Query)).Tables } - else { ($this.ExecuteWithResults($Query)).Tables[0] } - } -ErrorAction Ignore - - Update-TypeData -TypeName Microsoft.SqlServer.Management.Smo.Database -MemberName Invoke -MemberType ScriptMethod -Value { - param ( - $Command - ) - - $this.ExecuteNonQuery($Command) - } -ErrorAction Ignore -} \ No newline at end of file diff --git a/dbatools.psd1 b/dbatools.psd1 index 5f52e7124054..e3adff6b60a1 100644 --- a/dbatools.psd1 +++ b/dbatools.psd1 @@ -11,7 +11,7 @@ RootModule = 'dbatools.psm1' # Version number of this module. - ModuleVersion = '2.1.18' + ModuleVersion = '2.1.19' # ID used to uniquely identify this module GUID = '9d139310-ce45-41ce-8e8b-d76335aa1789' diff --git a/dbatools.psm1 b/dbatools.psm1 index b6468e48efa2..1ec91a8a1adb 100644 --- a/dbatools.psm1 +++ b/dbatools.psm1 @@ -1069,9 +1069,6 @@ if ($option.LoadTypes -or Write-ImportTime -Text "Updating type data" } -Import-Command -Path "$script:PSModuleRoot/bin/type-extensions.ps1" -Write-ImportTime -Text "Loading type extensions" - $loadedModuleNames = (Get-Module sqlserver, sqlps -ErrorAction Ignore).Name if ($loadedModuleNames -contains 'sqlserver' -or $loadedModuleNames -contains 'sqlps') { if (Get-DbatoolsConfigValue -FullName Import.SqlpsCheck) { diff --git a/private/functions/flowcontrol/Stop-Function.ps1 b/private/functions/flowcontrol/Stop-Function.ps1 index ae89d33b3e0a..51d4bd2b9b42 100644 --- a/private/functions/flowcontrol/Stop-Function.ps1 +++ b/private/functions/flowcontrol/Stop-Function.ps1 @@ -252,7 +252,7 @@ function Stop-Function { } # Extra insurance that it'll stop - Set-Variable -Name "__dbatools_interrupt_function_78Q9VPrM6999g6zo24Qn83m09XF56InEn4hFrA8Fwhu5xJrs6r" -Scope 1 -Value $true + Set-Variable -Name "__dbatools_interrupt_function_78Q9VPrM6999g6zo24Qn83m09XF56InEn4hFrA8Fwhu5xJrs6r" -Scope 1 -Value $true -WhatIf:$false throw $records[0] } @@ -273,7 +273,7 @@ function Stop-Function { } } else { # Make sure the function knows it should be stopping - Set-Variable -Name "__dbatools_interrupt_function_78Q9VPrM6999g6zo24Qn83m09XF56InEn4hFrA8Fwhu5xJrs6r" -Scope 1 -Value $true + Set-Variable -Name "__dbatools_interrupt_function_78Q9VPrM6999g6zo24Qn83m09XF56InEn4hFrA8Fwhu5xJrs6r" -Scope 1 -Value $true -WhatIf:$false return } diff --git a/public/Add-DbaRegServer.ps1 b/public/Add-DbaRegServer.ps1 index 75297e892f91..b65401ffecc1 100644 --- a/public/Add-DbaRegServer.ps1 +++ b/public/Add-DbaRegServer.ps1 @@ -56,9 +56,7 @@ function Add-DbaRegServer { .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 diff --git a/public/Add-DbaRegServerGroup.ps1 b/public/Add-DbaRegServerGroup.ps1 index 1457ca5e1963..95ac75900a77 100644 --- a/public/Add-DbaRegServerGroup.ps1 +++ b/public/Add-DbaRegServerGroup.ps1 @@ -37,9 +37,7 @@ function Add-DbaRegServerGroup { .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 diff --git a/public/Connect-DbaInstance.ps1 b/public/Connect-DbaInstance.ps1 index 048e3266e740..1ab2731993ca 100644 --- a/public/Connect-DbaInstance.ps1 +++ b/public/Connect-DbaInstance.ps1 @@ -142,6 +142,8 @@ function Connect-DbaInstance { Note that the token is valid for only one hour and cannot be renewed automatically. + Note that the returned SMO is not a fully functional SMO. It can only be used in a limited list of commands like Invoke-DbaQuery, Import-DbaCsv or Write-DbaDbTableData. + .PARAMETER DedicatedAdminConnection Connects using "ADMIN:" to create a dedicated admin connection (DAC) as a non-pooled connection. If the instance is on a remote server, the remote access has to be enabled via "Set-DbaSpConfigure -Name RemoteDacConnectionsEnabled -Value $true" or "sp_configure 'remote admin connections', 1". diff --git a/public/Copy-DbaDbQueryStoreOption.ps1 b/public/Copy-DbaDbQueryStoreOption.ps1 index 6198896a420b..b4375088158f 100644 --- a/public/Copy-DbaDbQueryStoreOption.ps1 +++ b/public/Copy-DbaDbQueryStoreOption.ps1 @@ -104,12 +104,6 @@ function Copy-DbaDbQueryStoreOption { $sourceDB = Get-DbaDatabase -SqlInstance $sourceServer -Database $SourceDatabase - if ($sourceServer.VersionMajor -eq 14) { - $QueryStoreOptions = $sourceDB.Query("SELECT max_plans_per_query AS MaxPlansPerQuery, wait_stats_capture_mode_desc AS WaitStatsCaptureMode FROM sys.database_query_store_options;", $sourceDB.Name) - } elseif ($sourceServer.VersionMajor -ge 15) { - $QueryStoreOptions = $sourceDB.Query("SELECT max_plans_per_query AS MaxPlansPerQuery, wait_stats_capture_mode_desc AS WaitStatsCaptureMode, capture_policy_execution_count AS CustomCapturePolicyExecutionCount, capture_policy_stale_threshold_hours AS CustomCapturePolicyStaleThresholdHours, capture_policy_total_compile_cpu_time_ms AS CustomCapturePolicyTotalCompileCPUTimeMS, capture_policy_total_execution_cpu_time_ms AS CustomCapturePolicyTotalExecutionCPUTimeMS FROM sys.database_query_store_options;", $sourceDB.Name) - } - foreach ($destinstance in $Destination) { if (!$DestinationDatabase -and !$Exclude -and !$AllDatabases) { @@ -152,6 +146,7 @@ function Copy-DbaDbQueryStoreOption { DestinationDatabaseID = $destDB.ID Type = "QueryStore Configuration" Status = $null + Notes = $null DateTime = [Dataplat.Dbatools.Utility.DbaDateTime](Get-Date) } @@ -191,8 +186,8 @@ function Copy-DbaDbQueryStoreOption { CaptureMode = $SourceQSConfig.QueryCaptureMode CleanupMode = $SourceQSConfig.SizeBasedCleanupMode StaleQueryThreshold = $SourceQSConfig.StaleQueryThresholdInDays - MaxPlansPerQuery = $QueryStoreOptions.MaxPlansPerQuery - WaitStatsCaptureMode = $QueryStoreOptions.WaitStatsCaptureMode + MaxPlansPerQuery = $SourceQSConfig.MaxPlansPerQuery + WaitStatsCaptureMode = $SourceQSConfig.WaitStatsCaptureMode } } elseif ($sourceServer.VersionMajor -ge 15) { $setDbaDbQueryStoreOptionParameters = @{ @@ -206,12 +201,12 @@ function Copy-DbaDbQueryStoreOption { CaptureMode = $SourceQSConfig.QueryCaptureMode CleanupMode = $SourceQSConfig.SizeBasedCleanupMode StaleQueryThreshold = $SourceQSConfig.StaleQueryThresholdInDays - MaxPlansPerQuery = $QueryStoreOptions.MaxPlansPerQuery - WaitStatsCaptureMode = $QueryStoreOptions.WaitStatsCaptureMode - CustomCapturePolicyExecutionCount = $QueryStoreOptions.CustomCapturePolicyExecutionCount - CustomCapturePolicyTotalCompileCPUTimeMS = $QueryStoreOptions.CustomCapturePolicyTotalCompileCPUTimeMS - CustomCapturePolicyTotalExecutionCPUTimeMS = $QueryStoreOptions.CustomCapturePolicyTotalExecutionCPUTimeMS - CustomCapturePolicyStaleThresholdHours = $QueryStoreOptions.CustomCapturePolicyStaleThresholdHours + MaxPlansPerQuery = $SourceQSConfig.MaxPlansPerQuery + WaitStatsCaptureMode = $SourceQSConfig.WaitStatsCaptureMode + CustomCapturePolicyExecutionCount = $SourceQSConfig.CustomCapturePolicyExecutionCount + CustomCapturePolicyTotalCompileCPUTimeMS = $SourceQSConfig.CustomCapturePolicyTotalCompileCPUTimeMS + CustomCapturePolicyTotalExecutionCPUTimeMS = $SourceQSConfig.CustomCapturePolicyTotalExecutionCPUTimeMS + CustomCapturePolicyStaleThresholdHours = $SourceQSConfig.CustomCapturePolicyStaleThresholdHours } } diff --git a/public/Disable-DbaDbEncryption.ps1 b/public/Disable-DbaDbEncryption.ps1 index 1ce0cb90cd60..7b306e86974d 100644 --- a/public/Disable-DbaDbEncryption.ps1 +++ b/public/Disable-DbaDbEncryption.ps1 @@ -34,7 +34,7 @@ function Disable-DbaDbEncryption { .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 disables you to catch exceptions with your own try/catch. + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. .PARAMETER WhatIf Shows what would happen if the command were to run. No actions are actually performed. diff --git a/public/Export-DbaRegServer.ps1 b/public/Export-DbaRegServer.ps1 index d2bd38c6bdc4..7ed7b4ff1968 100644 --- a/public/Export-DbaRegServer.ps1 +++ b/public/Export-DbaRegServer.ps1 @@ -41,9 +41,7 @@ function Export-DbaRegServer { .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 diff --git a/public/Export-DbaUser.ps1 b/public/Export-DbaUser.ps1 index da6d450cd30b..68da80cdf555 100644 --- a/public/Export-DbaUser.ps1 +++ b/public/Export-DbaUser.ps1 @@ -250,8 +250,6 @@ function Export-DbaUser { $FilePath = Get-ExportFilePath -Path $PSBoundParameters.Path -FilePath $PSBoundParameters.FilePath -Type sql -ServerName $db.Parent.Name -Unique } - # Store roles between users so if we hit the same one we don't create it again - $roles = @() $stepCounter = 0 foreach ($dbuser in $users) { @@ -274,14 +272,69 @@ function Export-DbaUser { } try { + <# + In this approach, we do not maintain a variable to track the roles that have been scripted. Our method involves a + consistent verification process for each user against the complete list of roles. This ensures that we dynamically + include only the roles to which a user belongs. For example, consider two users: user1 is associated with role1 and + role2, while user2 is associated with role1 and role3. + + Attempting to memorize the scripted roles could result in Transact-SQL (T-SQL) statements such as: + + IF NOT EXISTS (role1) + CREATE ROLE role1 + IF NOT EXISTS (role2) + CREATE ROLE role2 + IF NOT EXISTS (user1) + CREATE USER user1 + ADD user1 TO role1 + ADD user1 TO role2 + + -- And for another user: + + IF NOT EXISTS (role3) + CREATE ROLE role3 + IF NOT EXISTS (user2) + CREATE USER user2 + ADD user2 TO role1 + ADD user2 TO role3 + + However, this script inadvertently introduces a dependency issue. To ensure user2 is properly configured, the script + segment for user1 must be executed first due to the shared role1. To circumvent this issue and remove interdependencies, + we opt to match each user against all potential roles. Consequently, roles are scripted per user membership, resulting + in T-SQL like: + + IF NOT EXISTS (role1) + CREATE ROLE role1 + IF NOT EXISTS (role2) + CREATE ROLE role2 + IF NOT EXISTS (user1) + CREATE USER user1 + ADD user1 TO role1 + ADD user1 TO role2 + + -- And for another user: + + IF NOT EXISTS (role1) + CREATE ROLE role1 + IF NOT EXISTS (role3) + CREATE ROLE role3 + IF NOT EXISTS (user2) + CREATE USER user2 + ADD user2 TO role1 + ADD user2 TO role3 + + While this method may produce some redundant code (e.g., checking and creating role1 twice), it guarantees that each + portion of the script is self-sufficient and can be executed independently of others. Therefore, users can selectively + execute any segment of the script without concern for execution order or dependencies. + #> #Fixed Roles #Dependency Issue. Create Role, before add to role. - foreach ($rolePermission in ($db.Roles | Where-Object { $_.IsFixedRole -eq $false })) { - foreach ($rolePermissionScript in $rolePermission.Script($ScriptingOptionsObject)) { - if ($rolePermission.ToString() -notin $roles) { - $roles += , $rolePermission.ToString() + foreach ($role in ($db.Roles | Where-Object { $_.IsFixedRole -eq $false })) { + # Check if the user is a member of the role + $isUserMember = $role.EnumMembers() | Where-Object { $_ -eq $dbuser.Name } + if ($isUserMember) { + foreach ($rolePermissionScript in $role.Script($ScriptingOptionsObject)) { $outsql += "$($rolePermissionScript.ToString())" } - } } diff --git a/public/Export-DbatoolsConfig.ps1 b/public/Export-DbatoolsConfig.ps1 index 7324fb1d90fc..aaf5434b230d 100644 --- a/public/Export-DbatoolsConfig.ps1 +++ b/public/Export-DbatoolsConfig.ps1 @@ -40,8 +40,9 @@ function Export-DbatoolsConfig { (Note: Settings that were updated with the same value as the original default will still be considered changed) .PARAMETER EnableException - This parameters disables user-friendly warnings and enables the throwing of exceptions. - This is less user friendly, but allows catching exceptions in calling scripts. + 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: Module diff --git a/public/Get-DbaBackupInformation.ps1 b/public/Get-DbaBackupInformation.ps1 index 41b372366436..5c15c287c45e 100644 --- a/public/Get-DbaBackupInformation.ps1 +++ b/public/Get-DbaBackupInformation.ps1 @@ -78,8 +78,9 @@ function Get-DbaBackupInformation { When specified along with a path the command will import a previously exported BackupHistory object from an xml file. .PARAMETER EnableException - Replaces user friendly yellow warnings with bloody red exceptions of doom! - Use this if you want the function to throw terminating errors you want to catch. + 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: DisasterRecovery, Backup, Restore diff --git a/public/Get-DbaDbAssembly.ps1 b/public/Get-DbaDbAssembly.ps1 index ada1961d6de1..2f450bc52355 100644 --- a/public/Get-DbaDbAssembly.ps1 +++ b/public/Get-DbaDbAssembly.ps1 @@ -24,7 +24,7 @@ function Get-DbaDbAssembly { Specify an Assembly to be fetched. If not specified all Assemblies 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. + 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. diff --git a/public/Get-DbaDbDetachedFileInfo.ps1 b/public/Get-DbaDbDetachedFileInfo.ps1 index ad9e31b9f7ea..0d2333541576 100644 --- a/public/Get-DbaDbDetachedFileInfo.ps1 +++ b/public/Get-DbaDbDetachedFileInfo.ps1 @@ -86,8 +86,12 @@ function Get-DbaDbDetachedFileInfo { Stop-Function -Message "$servername cannot read the file $filepath. Is the database detached?" -Continue } + # Source: https://sqlserverbuilds.blogspot.com/2014/01/sql-server-internal-database-versions.html switch ($exactdbversion) { + 957 { $dbversion = "SQL Server 2022" } + 904 { $dbversion = "SQL Server 2019" } 869 { $dbversion = "SQL Server 2017" } + 868 { $dbversion = "SQL Server 2017" } 852 { $dbversion = "SQL Server 2016" } 782 { $dbversion = "SQL Server 2014" } 706 { $dbversion = "SQL Server 2012" } diff --git a/public/Get-DbaDbObjectTrigger.ps1 b/public/Get-DbaDbObjectTrigger.ps1 index 94f03f7c37e2..ec7a806cf8ba 100644 --- a/public/Get-DbaDbObjectTrigger.ps1 +++ b/public/Get-DbaDbObjectTrigger.ps1 @@ -31,7 +31,7 @@ function Get-DbaDbObjectTrigger { .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/ca + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. .NOTES Tags: Database, Trigger diff --git a/public/Get-DbaDbQueryStoreOption.ps1 b/public/Get-DbaDbQueryStoreOption.ps1 index 2500d44f2c5c..023e4c4204b0 100644 --- a/public/Get-DbaDbQueryStoreOption.ps1 +++ b/public/Get-DbaDbQueryStoreOption.ps1 @@ -89,9 +89,9 @@ function Get-DbaDbQueryStoreOption { $qso = $db.QueryStoreOptions if ($server.VersionMajor -eq 14) { - $QueryStoreOptions = $db.Query("SELECT max_plans_per_query AS MaxPlansPerQuery, wait_stats_capture_mode_desc AS WaitStatsCaptureMode FROM sys.database_query_store_options;", $db.Name) + $QueryStoreOptions = Invoke-DbaQuery -SqlInstance $server -Database $db.Name -Query "SELECT max_plans_per_query AS MaxPlansPerQuery, wait_stats_capture_mode_desc AS WaitStatsCaptureMode FROM sys.database_query_store_options;" -As PSObject } elseif ($server.VersionMajor -ge 15) { - $QueryStoreOptions = $db.Query("SELECT max_plans_per_query AS MaxPlansPerQuery, wait_stats_capture_mode_desc AS WaitStatsCaptureMode, capture_policy_execution_count AS CustomCapturePolicyExecutionCount, capture_policy_stale_threshold_hours AS CustomCapturePolicyStaleThresholdHours, capture_policy_total_compile_cpu_time_ms AS CustomCapturePolicyTotalCompileCPUTimeMS, capture_policy_total_execution_cpu_time_ms AS CustomCapturePolicyTotalExecutionCPUTimeMS FROM sys.database_query_store_options;", $db.Name) + $QueryStoreOptions = Invoke-DbaQuery -SqlInstance $server -Database $db.Name -Query "SELECT max_plans_per_query AS MaxPlansPerQuery, wait_stats_capture_mode_desc AS WaitStatsCaptureMode, capture_policy_execution_count AS CustomCapturePolicyExecutionCount, capture_policy_stale_threshold_hours AS CustomCapturePolicyStaleThresholdHours, capture_policy_total_compile_cpu_time_ms AS CustomCapturePolicyTotalCompileCPUTimeMS, capture_policy_total_execution_cpu_time_ms AS CustomCapturePolicyTotalExecutionCPUTimeMS FROM sys.database_query_store_options;" -As PSObject } Add-Member -Force -InputObject $qso -MemberType NoteProperty -Name ComputerName -Value $server.ComputerName diff --git a/public/Get-DbaDbTrigger.ps1 b/public/Get-DbaDbTrigger.ps1 index 02b62801196e..67e4a5887f88 100644 --- a/public/Get-DbaDbTrigger.ps1 +++ b/public/Get-DbaDbTrigger.ps1 @@ -28,7 +28,7 @@ function Get-DbaDbTrigger { .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/ca + Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch. .NOTES Tags: Database, Trigger diff --git a/public/Get-DbaKbUpdate.ps1 b/public/Get-DbaKbUpdate.ps1 index ec59e4ea5a6a..febf26844768 100644 --- a/public/Get-DbaKbUpdate.ps1 +++ b/public/Get-DbaKbUpdate.ps1 @@ -25,9 +25,7 @@ function Get-DbaKbUpdate { .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 diff --git a/public/Get-DbaLastBackup.ps1 b/public/Get-DbaLastBackup.ps1 index 2fde58ffcac7..4609a188779d 100644 --- a/public/Get-DbaLastBackup.ps1 +++ b/public/Get-DbaLastBackup.ps1 @@ -25,7 +25,9 @@ function Get-DbaLastBackup { Specifies one or more database(s) to exclude from processing. .PARAMETER EnableException - If this switch is enabled exceptions will be thrown to the caller, which will need to perform its own exception processing. Otherwise, the function will try to catch the exception, interpret it and provide a friendly error message. + 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: DisasterRecovery, Backup diff --git a/public/Get-DbaMsdtc.ps1 b/public/Get-DbaMsdtc.ps1 index 10f611fc5377..0a9c1285cbd3 100644 --- a/public/Get-DbaMsdtc.ps1 +++ b/public/Get-DbaMsdtc.ps1 @@ -15,11 +15,10 @@ function Get-DbaMsdtc { Alternative credential .PARAMETER EnableException - By default in most of our commands, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. + 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. - This command, however, gifts you with "sea of red" exceptions, by default, because it is useful for advanced scripting. - - Using this switch turns our "nice by default" feature on which makes errors into pretty warnings. .NOTES Tags: Msdtc, dtc, General Author: Klaas Vandenberghe (@powerdbaklaas) diff --git a/public/Get-DbaPermission.ps1 b/public/Get-DbaPermission.ps1 index e4ca773bdbf1..121cbca1ead8 100644 --- a/public/Get-DbaPermission.ps1 +++ b/public/Get-DbaPermission.ps1 @@ -39,7 +39,9 @@ function Get-DbaPermission { If this switch is enabled, permissions on system securables will be excluded. .PARAMETER EnableException - If this switch is enabled exceptions will be thrown to the caller, which will need to perform its own exception processing. Otherwise, the function will try to catch the exception, interpret it and provide a friendly error message. + 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: Permissions, Instance, Database, Security diff --git a/public/Get-DbaRegServer.ps1 b/public/Get-DbaRegServer.ps1 index ae144a8deaec..fc49d371250e 100644 --- a/public/Get-DbaRegServer.ps1 +++ b/public/Get-DbaRegServer.ps1 @@ -44,9 +44,7 @@ function Get-DbaRegServer { .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 diff --git a/public/Get-DbaRegServerGroup.ps1 b/public/Get-DbaRegServerGroup.ps1 index bd434491a9c2..1bc87cbd5a24 100644 --- a/public/Get-DbaRegServerGroup.ps1 +++ b/public/Get-DbaRegServerGroup.ps1 @@ -27,9 +27,7 @@ function Get-DbaRegServerGroup { .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 diff --git a/public/Get-DbaServerRole.ps1 b/public/Get-DbaServerRole.ps1 index 23438c84b04a..8dd8320b389e 100644 --- a/public/Get-DbaServerRole.ps1 +++ b/public/Get-DbaServerRole.ps1 @@ -26,7 +26,9 @@ function Get-DbaServerRole { Filter the fixed server-level roles. Only applies to SQL Server 2017 that supports creation of server-level roles. .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. + 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: Role diff --git a/public/Get-DbaStartupParameter.ps1 b/public/Get-DbaStartupParameter.ps1 index 8a6f1ce18642..3f14ee1e2efe 100644 --- a/public/Get-DbaStartupParameter.ps1 +++ b/public/Get-DbaStartupParameter.ps1 @@ -22,7 +22,9 @@ function Get-DbaStartupParameter { If this switch is enabled, simplified output will be produced including only Server, Master Data path, Master Log path, ErrorLog, TraceFlags and ParameterString. .PARAMETER EnableException - If this switch is enabled, exceptions will be thrown to the caller, which will need to perform its own exception processing. Otherwise, the function will try to catch the exception, interpret it and provide a friendly error message. + 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: WSMan, SQLWMI, Memory, Startup diff --git a/public/Get-DbaTopResourceUsage.ps1 b/public/Get-DbaTopResourceUsage.ps1 index 40b186e69ff9..e515ccf137a3 100644 --- a/public/Get-DbaTopResourceUsage.ps1 +++ b/public/Get-DbaTopResourceUsage.ps1 @@ -254,7 +254,7 @@ function Get-DbaTopResourceUsage { process { foreach ($instance in $SqlInstance) { try { - $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10 -StatementTimeout 0 + $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10 } catch { Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue } diff --git a/public/Get-DbaWaitResource.ps1 b/public/Get-DbaWaitResource.ps1 index b5deea40e389..dcb34d1c192f 100644 --- a/public/Get-DbaWaitResource.ps1 +++ b/public/Get-DbaWaitResource.ps1 @@ -25,8 +25,9 @@ function Get-DbaWaitResource { If this switch provided also returns the value of the row being waited on with KEY wait resources .PARAMETER EnableException - Replaces user friendly yellow warnings with bloody red exceptions of doom! - Use this if you want the function to throw terminating errors you want to catch. + 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: Diagnostic, Pages, DBCC diff --git a/public/Get-DbaXEObject.ps1 b/public/Get-DbaXEObject.ps1 index fa1234f522e5..1dcb5bac1902 100644 --- a/public/Get-DbaXEObject.ps1 +++ b/public/Get-DbaXEObject.ps1 @@ -29,7 +29,9 @@ function Get-DbaXEObject { Type .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. + 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: ExtendedEvent, XE, XEvent diff --git a/public/Get-DbatoolsError.ps1 b/public/Get-DbatoolsError.ps1 index e75a1274d1bb..ce5bdf89f224 100644 --- a/public/Get-DbatoolsError.ps1 +++ b/public/Get-DbatoolsError.ps1 @@ -62,6 +62,6 @@ function Get-DbatoolsError { $First = $global:error.Count } - $global:error | Where-Object ScriptStackTrace -match dbatools | Select-Object -First $First -Last $Last -Skip $Skip -Property CategoryInfo, ErrorDetails, Exception, FullyQualifiedErrorId, InvocationInfo, PipelineIterationInfo, PSMessageDetails, ScriptStackTrace, TargetObject + $global:error | Where-Object FullyQualifiedErrorId -match dbatools | Select-Object -First $First -Last $Last -Skip $Skip -Property CategoryInfo, ErrorDetails, Exception, FullyQualifiedErrorId, InvocationInfo, PipelineIterationInfo, PSMessageDetails, ScriptStackTrace, TargetObject } } \ No newline at end of file diff --git a/public/Import-DbaCsv.ps1 b/public/Import-DbaCsv.ps1 index c3adfbde3db0..df191514b7d4 100644 --- a/public/Import-DbaCsv.ps1 +++ b/public/Import-DbaCsv.ps1 @@ -456,7 +456,7 @@ function Import-DbaCsv { $elapsed = [System.Diagnostics.Stopwatch]::StartNew() # Open Connection to SQL Server try { - $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database -StatementTimeout 0 -MinimumVersion 9 + $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -Database $Database -MinimumVersion 9 $sqlconn = $server.ConnectionContext.SqlConnectionObject if ($sqlconn.State -ne 'Open') { $sqlconn.Open() diff --git a/public/Import-DbaRegServer.ps1 b/public/Import-DbaRegServer.ps1 index d86184bd2226..0c67f51a0fd4 100644 --- a/public/Import-DbaRegServer.ps1 +++ b/public/Import-DbaRegServer.ps1 @@ -29,9 +29,7 @@ function Import-DbaRegServer { .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 diff --git a/public/Import-DbatoolsConfig.ps1 b/public/Import-DbatoolsConfig.ps1 index 756ca1def7f0..ba258ae90252 100644 --- a/public/Import-DbatoolsConfig.ps1 +++ b/public/Import-DbatoolsConfig.ps1 @@ -30,8 +30,9 @@ function Import-DbatoolsConfig { Rather than applying the setting, return the configuration items that would have been applied. .PARAMETER EnableException - This parameters disables user-friendly warnings and enables the throwing of exceptions. - This is less user friendly, but allows catching exceptions in calling scripts. + 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: Module diff --git a/public/Install-DbaInstance.ps1 b/public/Install-DbaInstance.ps1 index 13a98f78a447..2d6f7b2a6c45 100644 --- a/public/Install-DbaInstance.ps1 +++ b/public/Install-DbaInstance.ps1 @@ -248,6 +248,12 @@ function Install-DbaInstance { Install SQL Server 2016 instance into D:\Root drive, set default data folder as E: and default logs folder as L:. Perform volume maintenance tasks permission is granted. MyDomain\SvcSqlServer is used as a service account for SqlServer. + .Example + PS C:\> $svcAcc = [PSCredential]::new("MyDomain\SvcSqlServer$", [SecureString]::new()) + PS C:\> Install-DbaInstance -Version 2016 -InstancePath D:\Root -DataPath E: -LogPath L: -PerformVolumeMaintenanceTasks -EngineCredential $svcAcc + + The same as the last example except MyDomain\SvcSqlServer is now a Managed Service Account (MSA). + .Example PS C:\> $config = @{ >> AGTSVCSTARTUPTYPE = "Manual" @@ -823,4 +829,4 @@ function Install-DbaInstance { $actionPlan | Invoke-Parallel -ImportModules -ImportVariables @invokeParallelSplat } } -} \ No newline at end of file +} diff --git a/public/Invoke-DbaAdvancedRestore.ps1 b/public/Invoke-DbaAdvancedRestore.ps1 index 98bad3d9201c..1f311eddae72 100644 --- a/public/Invoke-DbaAdvancedRestore.ps1 +++ b/public/Invoke-DbaAdvancedRestore.ps1 @@ -95,8 +95,9 @@ function Invoke-DbaAdvancedRestore { By default the restore will stop at the first occurence of StopMark found in the chain, passing a datetime where will cause it to stop the first StopMark atfer that datetime .PARAMETER EnableException - Replaces user friendly yellow warnings with bloody red exceptions of doom! - Use this if you want the function to throw terminating errors you want to catch. + 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: Restore, Backup diff --git a/public/Invoke-DbaDbLogShipping.ps1 b/public/Invoke-DbaDbLogShipping.ps1 index 2dbdc3a44ca7..70bdbcdddc76 100644 --- a/public/Invoke-DbaDbLogShipping.ps1 +++ b/public/Invoke-DbaDbLogShipping.ps1 @@ -342,7 +342,9 @@ function Invoke-DbaDbLogShipping { Prompts you for confirmation before executing any changing operations within the command. .PARAMETER EnableException - Use this switch to disable any kind of verbose messages + 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 Force The force parameter will ignore some errors in the parameters and assume defaults. diff --git a/public/Invoke-DbaDbUpgrade.ps1 b/public/Invoke-DbaDbUpgrade.ps1 index c2ce4a0dcc39..41cce5af3b4f 100644 --- a/public/Invoke-DbaDbUpgrade.ps1 +++ b/public/Invoke-DbaDbUpgrade.ps1 @@ -132,7 +132,7 @@ function Invoke-DbaDbUpgrade { foreach ($instance in $SqlInstance) { try { - $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -StatementTimeout 0 + $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential } catch { Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue } diff --git a/public/Move-DbaDbFile.ps1 b/public/Move-DbaDbFile.ps1 index d029aded22ff..3c83a914ea27 100644 --- a/public/Move-DbaDbFile.ps1 +++ b/public/Move-DbaDbFile.ps1 @@ -50,9 +50,7 @@ function Move-DbaDbFile { .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 diff --git a/public/Move-DbaRegServer.ps1 b/public/Move-DbaRegServer.ps1 index 8a8d17e8a3b8..f2cd30919cec 100644 --- a/public/Move-DbaRegServer.ps1 +++ b/public/Move-DbaRegServer.ps1 @@ -36,9 +36,7 @@ function Move-DbaRegServer { .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 diff --git a/public/Move-DbaRegServerGroup.ps1 b/public/Move-DbaRegServerGroup.ps1 index a6e0f2577ec6..2563b85b83c1 100644 --- a/public/Move-DbaRegServerGroup.ps1 +++ b/public/Move-DbaRegServerGroup.ps1 @@ -33,9 +33,7 @@ function Move-DbaRegServerGroup { .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 diff --git a/public/New-DbaAzAccessToken.ps1 b/public/New-DbaAzAccessToken.ps1 index 9a9a1bf1fa94..8387b58e2447 100644 --- a/public/New-DbaAzAccessToken.ps1 +++ b/public/New-DbaAzAccessToken.ps1 @@ -45,11 +45,9 @@ function New-DbaAzAccessToken { Store where the Azure MSI certificate is stored .PARAMETER EnableException - By default in most of our commands, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. - - This command, however, gifts you with "sea of red" exceptions, by default, because it is useful for advanced scripting. - - Using this switch turns our "nice by default" feature on which makes errors into pretty warnings. + 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: Connect, Connection, Azure diff --git a/public/New-DbaDbUser.ps1 b/public/New-DbaDbUser.ps1 index 082d11ef6c8a..8416622863cf 100644 --- a/public/New-DbaDbUser.ps1 +++ b/public/New-DbaDbUser.ps1 @@ -1,13 +1,13 @@ function New-DbaDbUser { <# .SYNOPSIS - Creates a new user for the specified database. + Creates a new user for the specified database(s). .DESCRIPTION - Creates a new user for a specified database with provided specifications. + Creates a new user for the specified database(s) with provided specifications. .PARAMETER SqlInstance - The target SQL Server instance or instances. Defaults to the default instance on localhost. + The target SQL Server instance or instances. .PARAMETER SqlCredential Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential). @@ -17,30 +17,31 @@ function New-DbaDbUser { For MFA support, please use Connect-DbaInstance. .PARAMETER Database - Specifies the database(s) to process. Options for this list are auto-populated from the server. If unspecified, all user databases will be processed. + Specifies one or more database(s) to process. If unspecified, all user databases will be processed. .PARAMETER ExcludeDatabase - Specifies the database(s) to exclude from processing. Options for this list are auto-populated from the server. By default, system databases are excluded. + Specifies one or more database(s) to exclude from processing. .PARAMETER IncludeSystem - If this switch is enabled, the user will be added to system databases. This switch will be ignored if -Database is used. + If this switch is enabled, also system databases will be processed. - .PARAMETER Login - When specified, the user will be associated to this SQL login and have the same name as the Login. + .PARAMETER User + When specified, the user will have this name. If not specified but -Login is used, the user will have the same name as the login. - .PARAMETER Username - When specified, the user will have this name. + .PARAMETER Login + When specified, the user will be associated to this SQL login. .PARAMETER Password - When specified, the user will be created as a contained user. Standalone databases partial containment should be turned on to succeed. By default, in Azure SQL databases this is turned on. - - .PARAMETER DefaultSchema - The default database schema for the user. If not specified this value will default to dbo. + When specified, the user will be created as a contained user. + Standalone databases partial containment should be turned on to succeed. By default, in Azure SQL databases this is turned on. .PARAMETER ExternalProvider - Specifies that the user is for Azure AD Authentication. + When specified, the user will be created for Azure AD Authentication. Equivalent to T-SQL: 'CREATE USER [claudio@********.onmicrosoft.com] FROM EXTERNAL PROVIDER` + .PARAMETER DefaultSchema + The default database schema for the user. If not specified this value will default to dbo. + .PARAMETER Force If user exists, drop and recreate. @@ -69,165 +70,188 @@ function New-DbaDbUser { .EXAMPLE PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Login user1 - Creates a new sql user with login named user1 in the specified database. + Creates a new sql user named user1 for the login user1 in the database DB1. .EXAMPLE - PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Username user1 + PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -User user1 - Creates a new sql user without login named user1 in the specified database. + Creates a new sql user named user1 without login in the database DB1. .EXAMPLE - PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Login Login1 -Username user1 + PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -User user1 -Login login1 - Creates a new sql user named user1 mapped to Login1 in the specified database. + Creates a new sql user named user1 for the login login1 in the database DB1. .EXAMPLE - PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Login Login1 -Username user1 -DefaultSchema schema1 + PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -User user1 -Login Login1 -DefaultSchema schema1 - Creates a new sql user named user1 mapped to Login1 in the specified database and specifies the default schema to be schema1. + Creates a new sql user named user1 for the login login1 in the database DB1 and specifies the default schema to be schema1. .EXAMPLE - PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Username "claudio@********.onmicrosoft.com" -ExternalProvider + PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -User "claudio@********.onmicrosoft.com" -ExternalProvider - Creates a new sql user named 'claudio@********.onmicrosoft.com' mapped to Azure Active Directory (AAD) in the specified database. + Creates a new sql user named 'claudio@********.onmicrosoft.com' mapped to Azure Active Directory (AAD) in the database DB1. .EXAMPLE - PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Username user1 -Password (ConvertTo-SecureString -String "DBATools" -AsPlainText) + PS C:\> New-DbaDbUser -SqlInstance sqlserver2014 -Database DB1 -Username user1 -Password (ConvertTo-SecureString -String "DBATools" -AsPlainText -Force) - Creates a new cointained sql user named user1 in the database given database with the password specified. + Creates a new contained sql user named user1 in the database DB1 with the password specified. #> + + ### This command has more comments than other commands, because it should act as an example for other commands. + ### These extra lines start with "###" and should help new contributors to understand why we code the way we do. + + ### All commands that change objects must use SupportsShouldProcess to support -WhatIf. + ### All commands that add or change objects (New-... or Set-...) must use ConfirmImpact = "Medium". + ### All commands that drop existing objects (Remove-...) must use ConfirmImpact = "High". + ### For most of the commands, we try to not use parameter sets and try to check valid parameter combinations inside of the command to be able to give the user a "nice" feedback. + ### But this is an example of a command that uses parameter sets, which gives better help output. [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Medium")] param( - [parameter(Mandatory, Position = 1)] + ### All commands that need a connection to an instance use the following two parameters in the way we define here. + ### This supports parameter by position for the parameter SqlInstance and makes this a mandatory parameter. + ### Exception: Some commands allow pipeline input, in this case the parameter is not mandatory. + [Parameter(Mandatory, Position = 1)] [DbaInstanceParameter[]]$SqlInstance, [PSCredential]$SqlCredential, + ### All commands that need to work with databases or database objects use the following three parameters. [string[]]$Database, [string[]]$ExcludeDatabase, - [switch]$IncludeSystem = $False, + [switch]$IncludeSystem, + ### The following parameters are specific to the objects that the command works with, in this case a database user. + ### We start with the name of the object, in this case the name of the user that will be created. + ### For the default parameter set Login, the name of the user can be set to the mandatory parameter Login, in all other cases, we need the name of the user. + [Parameter(ParameterSetName = "Login")] + [Parameter(Mandatory, ParameterSetName = "NoLogin")] + [Parameter(Mandatory, ParameterSetName = "ContainedSQLUser")] + [Parameter(Mandatory, ParameterSetName = "ContainedAADUser")] + [Alias("Username")] + [string]$User, + ### Now we add parameters to specify the individual attributes for the object. We start with parameters that are mandatory for parameter sets. [Parameter(Mandatory, ParameterSetName = "Login")] [string]$Login, - [Parameter(ParameterSetName = "Login", Mandatory = $False)] - [Parameter(Mandatory, ParameterSetName = "NoLogin")] - [Parameter(ParameterSetName = "ContainedSQLUser", Mandatory = $True)] - [Parameter(ParameterSetName = "ContainedAADUser", Mandatory = $True)] - [string]$Username, - [string]$DefaultSchema = 'dbo', - [Parameter(ParameterSetName = "ContainedSQLUser", Mandatory = $True)] - [securestring]$Password, - [Parameter(ParameterSetName = "ContainedAADUser", Mandatory = $True)] + ### If we need to pass a password to the command, we always use the type securestring and name the parameter SecurePassword. Here we only use the alias for backwords compatibility. + [Parameter(Mandatory, ParameterSetName = "ContainedSQLUser")] + [Alias("Password")] + [securestring]$SecurePassword, + [Parameter(Mandatory, ParameterSetName = "ContainedAADUser")] [switch]$ExternalProvider, + ### Now we add parameters to specify the individual attributes for the object that are not specific for a parameter set. + ### As we want to use the schema dbo in most cases, we use default values in those cases. + [string]$DefaultSchema = 'dbo', + ### All commands that create new objects have a switch parameter Force to drop and re-create the object in case it already exists. + ### Sometimes, this parameter also changes the ConfirmPreference to "none". This way, -WhatIf and -Force cannot be used together. So this has to be removed everywhere. + ### This parameter is always the second last parameter. [switch]$Force, + ### All public commands have a switch parameter called EnableException as the last parameter. This changes the behavior of Stop-Function inside of the command. [switch]$EnableException ) begin { - $connParam = @{ } - if ($SqlCredential) { $connParam.SqlCredential = $SqlCredential } - - if ($Force) { $ConfirmPreference = 'none' } - - # When user is created from login and no user name is provided then login name will be used as the user name - if ($Login -and -not($Username)) { - $Username = $Login + ### To help analyzing bugs in commands using parameter sets, we write the used parameter set to verbose output. + Write-Message -Level Verbose -Message "Using parameter set $($PSCmdlet.ParameterSetName)." + + ### To help analyzing bugs, we write at least one line to verbose output per code path. This can also be used as a kind of comment. + ### Changing parameter values is only allowed in the begin block, so that every execution of the process block or the instance loop in the process block has the same set of parameter values. + if ($Login -and -not $User) { + Write-Message -Level Verbose -Message "No user name provided, so login name [$Login] will be used as user name." + $User = $Login } - #Set appropriate user type - #Removed SQLLogin user type. This is deprecated and the alternate is to map to SqlUser. Reference https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.management.smo.usertype?view=sql-smo-160 + # Set appropriate user type based on provided parameters. + # See https://learn.microsoft.com/en-us/dotnet/api/microsoft.sqlserver.management.smo.usertype for details. if ($ExternalProvider) { - Write-Message -Level Verbose -Message "Using UserType: External" + Write-Message -Level Verbose -Message "Using UserType [External]." $userType = [Microsoft.SqlServer.Management.Smo.UserType]::External - } elseif ($Password -or $Login) { - Write-Message -Level Verbose -Message "Using UserType: SqlUser" + } elseif ($SecurePassword -or $Login) { + Write-Message -Level Verbose -Message "Using UserType [SqlUser]." $userType = [Microsoft.SqlServer.Management.Smo.UserType]::SqlUser } else { - Write-Message -Level Verbose -Message "Using UserType: NoLogin" + Write-Message -Level Verbose -Message "Using UserType [NoLogin]." $userType = [Microsoft.SqlServer.Management.Smo.UserType]::NoLogin } } process { - + ### Every process block starts with a loop through the parameter SqlInstance. + ### Inside of the loop the current instance is named "instance". + ### The first thing we do is to connect to the instance and save the returned server SMO in a variable called server. + ### If this fails, we notify the user and continue with the next instance. + ### The next six lines are (nearly) always the same for every command that connects to one or more instances. foreach ($instance in $SqlInstance) { - #prepare parameter values - $connParam.SqlInstance = $instance - $getDbParam = $connParam.Clone() - $getDbParam.OnlyAccessible = $True - if ($Database) { - $getDbParam.Database = $Database - } - if (-not $IncludeSystem) { - $getDbParam.ExcludeSystem = $True - } - if ($ExcludeDatabase) { - $getDbParam.ExcludeDatabase = $ExcludeDatabase - } - - # Is the login exist? - if ($Login -and (-not(Get-DbaLogin @connParam -Login $Login))) { - Stop-Function -Message "Invalid Login: [$Login] is not found on [$instance], skipping." -Target $instance -Continue -EnableException $False + try { + $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential + } catch { + Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue } - $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 + ### Run checks as early as possible. + ### After connecting to the instance, run checks that need a connected instance. + ### As the check might be successful on the next instance in the loop, use -Continue. + ### In the messages, all strings should be surrounded by "[]", but all SMO variables will get "[]" automaticaly by their .ToString() method. + if ($Login -and -not $server.Logins[$Login]) { + Stop-Function -Message "Login [$Login] not found on instance $server" -Continue } - foreach ($db in $Database) { - $dbSmo = $databases | Where-Object Name -eq $db - - #Check if the database exists and online - if (-not($dbSmo)) { - Stop-Function -Message "Invalid Database: [$db] is not found in the instance [$instance], skipping." -Continue -EnableException $False + ### As we need the database object(s) to be able to add a new users to it, we have to filter the databases of the instance based on the provided parameters. + ### We use Get-DbaDatabase here, because that command does all we need. + ### We generally avoid to use other commands as they add more load and prefer to use the SMO directly. But in this case there is not much extra work. + ### The following lines are always the same for all commands that work on a set of databases. + $databases = Get-DbaDatabase -SqlInstance $server -Database $Database -ExcludeDatabase $ExcludeDatabase -ExcludeSystem:$(-not $IncludeSystem) + ### Commands that need to change the database test for IsUpdateable, other commands test for IsAccessible. + $databases = $databases | Where-Object IsUpdateable + foreach ($db in $databases) { + ### Where should be a verbose message at the start of each loop to help analyzing issues. + Write-Message -Level Verbose -Message "Processing database $db on instance $server." + + ### Run checks that need a database object. The same rules as for the instance checks apply. + if (-not $db.Schemas[$DefaultSchema]) { + Stop-Function -Message "Schema [$DefaultSchema] does not exist in database $db on instance $server" -Continue } - #prepare user query param - $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) { - if ($Pscmdlet.ShouldProcess($dbSmo, "Creating user $Username")) { - Write-Message -Level Verbose -Message "Add user [$Username] to database [$dbSmo] on [$instance]" - - #smo param builder - $smoUser = New-Object Microsoft.SqlServer.Management.Smo.User - $smoUser.Parent = $dbSmo - $smoUser.Name = $Username - if ($Login) { $smoUser.Login = $Login } - $smoUser.UserType = $userType - $smoUser.DefaultSchema = $DefaultSchema - - #Check if the user exists already - $userExists = Get-DbaDbUser @userParam - if ($userExists -and -not($Force)) { - Stop-Function -Message "User [$Username] already exists in the database $dbSmo on [$instance] and -Force was not specified, skipping." -Target $Username -Continue -EnableException $False - } elseif ($userExists -and $Force) { + + ### As a last check, check for existance of the object that should be created. + ### Depending on the usage of -Force, drop the object or continue with the next database. + if ($db.Users[$User]) { + if ($Force) { + if ($Pscmdlet.ShouldProcess("User [$User] in database $db on instance $server", "Dropping user")) { try { - Write-Message -Level Verbose -Message "FORCE is used, user [$Username] will be dropped in the database $dbSmo on [$instance]" - $null = Remove-DbaDbUser @userParam -Force + $db.Users[$User].Drop() } catch { - Stop-Function -Message "Could not remove existing user [$Username] in the database $dbSmo on [$instance], skipping." -Target $User -ErrorRecord $_ -Continue + Stop-Function -Message "Dropping user [$User] in database $db on instance $server failed" -ErrorRecord $_ -Continue } } + } else { + Stop-Function -Message "User [$User] already exists in database $db on instance $server and -Force was not specified" -Continue + } + } - #Create the user - try { - if ($Password) { - $smoUser.Create($Password) - } else { $smoUser.Create() } - #Verfiy the user creation - Get-DbaDbUser @userParam - } catch { - Stop-Function -Message "Failed to add user [$Username] in $dbSmo to [$instance]" -Category InvalidOperation -ErrorRecord $_ -Target $instance -Continue + if ($Pscmdlet.ShouldProcess("User [$User] in database $db on instance $server", "Creating user")) { + try { + $newUser = New-Object Microsoft.SqlServer.Management.Smo.User + $newUser.Parent = $db + $newUser.Name = $User + if ($Login) { + $newUser.Login = $Login + } + $newUser.UserType = $userType + $newUser.DefaultSchema = $DefaultSchema + if ($SecurePassword) { + $newUser.Create($SecurePassword) + } else { + $newUser.Create() } + ### Add the common dbatools properties to the new object + Add-Member -Force -InputObject $newUser -MemberType NoteProperty -Name ComputerName -value $server.ComputerName + Add-Member -Force -InputObject $newUser -MemberType NoteProperty -Name InstanceName -value $server.ServiceName + Add-Member -Force -InputObject $newUser -MemberType NoteProperty -Name SqlInstance -value $server.DomainInstanceName + Add-Member -Force -InputObject $newUser -MemberType NoteProperty -Name Database -value $db.Name + + ### Output the new object + Select-DefaultView -InputObject $newUser -Property ComputerName, InstanceName, SqlInstance, Database, Name, LoginType, Login, AuthenticationType, DefaultSchema + } catch { + Stop-Function -Message "Creating user [$User] in database $db on instance $server failed" -ErrorRecord $_ -Continue } - } else { - Stop-Function -Message "Invalid DefaultSchema: [$DefaultSchema] is not found in the database $dbSmo on [$instance], skipping." -Continue -EnableException $False } } } diff --git a/public/Read-DbaBackupHeader.ps1 b/public/Read-DbaBackupHeader.ps1 index 7b237a57ac74..0338b83df591 100644 --- a/public/Read-DbaBackupHeader.ps1 +++ b/public/Read-DbaBackupHeader.ps1 @@ -29,7 +29,8 @@ function Read-DbaBackupHeader { Name of the SQL Server credential that should be used for Azure storage access. .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. + 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 diff --git a/public/Register-DbatoolsConfig.ps1 b/public/Register-DbatoolsConfig.ps1 index 1636cbc226c8..697ed03d155a 100644 --- a/public/Register-DbatoolsConfig.ps1 +++ b/public/Register-DbatoolsConfig.ps1 @@ -28,8 +28,9 @@ function Register-DbatoolsConfig { Legal values: UserDefault, UserMandatory, SystemDefault, SystemMandatory .PARAMETER EnableException - This parameters disables user-friendly warnings and enables the throwing of exceptions. - This is less user friendly, but allows catching exceptions in calling scripts. + 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: Module diff --git a/public/Remove-DbaDbLogShipping.ps1 b/public/Remove-DbaDbLogShipping.ps1 index a97027011b85..358c08c8f818 100644 --- a/public/Remove-DbaDbLogShipping.ps1 +++ b/public/Remove-DbaDbLogShipping.ps1 @@ -48,7 +48,9 @@ Prompts you for confirmation before executing any changing operations within the command. .PARAMETER EnableException - Use this switch to disable any kind of verbose messages + 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: LogShipping diff --git a/public/Remove-DbaRegServer.ps1 b/public/Remove-DbaRegServer.ps1 index d9fe74f8e61c..efdc097ed808 100644 --- a/public/Remove-DbaRegServer.ps1 +++ b/public/Remove-DbaRegServer.ps1 @@ -36,9 +36,7 @@ function Remove-DbaRegServer { .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 diff --git a/public/Remove-DbaRegServerGroup.ps1 b/public/Remove-DbaRegServerGroup.ps1 index 219ec1b7e92a..cf7982fff7e8 100644 --- a/public/Remove-DbaRegServerGroup.ps1 +++ b/public/Remove-DbaRegServerGroup.ps1 @@ -30,9 +30,7 @@ function Remove-DbaRegServerGroup { .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 diff --git a/public/Reset-DbatoolsConfig.ps1 b/public/Reset-DbatoolsConfig.ps1 index e437247beb3c..17f3c6d89215 100644 --- a/public/Reset-DbatoolsConfig.ps1 +++ b/public/Reset-DbatoolsConfig.ps1 @@ -25,8 +25,9 @@ function Reset-DbatoolsConfig { Used in conjunction with the -Module parameter to select which settings to reset using wildcard comparison. .PARAMETER EnableException - This parameters disables user-friendly warnings and enables the throwing of exceptions. - This is less user friendly, but allows catching exceptions in calling scripts. + 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 Confirm If this switch is enabled, you will be prompted for confirmation before executing any operations that change state. diff --git a/public/Save-DbaKbUpdate.ps1 b/public/Save-DbaKbUpdate.ps1 index cf53b514283f..96baa4c6b288 100644 --- a/public/Save-DbaKbUpdate.ps1 +++ b/public/Save-DbaKbUpdate.ps1 @@ -28,9 +28,7 @@ function Save-DbaKbUpdate { .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 diff --git a/public/Set-DbaDbCompression.ps1 b/public/Set-DbaDbCompression.ps1 index 1de14783c7ae..417d45c1230d 100644 --- a/public/Set-DbaDbCompression.ps1 +++ b/public/Set-DbaDbCompression.ps1 @@ -128,7 +128,7 @@ function Set-DbaDbCompression { $starttime = Get-Date foreach ($instance in $SqlInstance) { try { - $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10 -StatementTimeout 0 + $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 10 } catch { Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue } diff --git a/public/Show-DbaDbList.ps1 b/public/Show-DbaDbList.ps1 index 4e959c65db08..e154c221890f 100644 --- a/public/Show-DbaDbList.ps1 +++ b/public/Show-DbaDbList.ps1 @@ -26,11 +26,9 @@ function Show-DbaDbList { Specify a database to have selected when the window appears. .PARAMETER EnableException - By default in most of our commands, when something goes wrong we try to catch it, interpret it and give you a friendly warning message. - - This command, however, gifts you with "sea of red" exceptions, by default, because it is useful for advanced scripting. - - Using this switch turns our "nice by default" feature on which makes errors into pretty warnings. + 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: Database, FileSystem diff --git a/public/Test-DbaLinkedServerConnection.ps1 b/public/Test-DbaLinkedServerConnection.ps1 index 784dd4b0d544..2e8834491cf8 100644 --- a/public/Test-DbaLinkedServerConnection.ps1 +++ b/public/Test-DbaLinkedServerConnection.ps1 @@ -18,7 +18,6 @@ function Test-DbaLinkedServerConnection { .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. diff --git a/public/Test-DbaOptimizeForAdHoc.ps1 b/public/Test-DbaOptimizeForAdHoc.ps1 index d4b823c49374..cbe1f94d7ab2 100644 --- a/public/Test-DbaOptimizeForAdHoc.ps1 +++ b/public/Test-DbaOptimizeForAdHoc.ps1 @@ -22,7 +22,9 @@ function Test-DbaOptimizeForAdHoc { 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. + 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: Configure, SPConfigure diff --git a/public/Write-DbaDbTableData.ps1 b/public/Write-DbaDbTableData.ps1 index 27abc87d6d70..e4d0d457d3b6 100644 --- a/public/Write-DbaDbTableData.ps1 +++ b/public/Write-DbaDbTableData.ps1 @@ -468,6 +468,7 @@ function Write-DbaDbTableData { } #endregion Connect to server + #region Resolve Full Qualified Table Name if ($server.ServerType -ne 'SqlAzureDatabase') { <# Skip adding database name to Fully Qualified Tablename for Azure SQL DB @@ -502,47 +503,30 @@ function Write-DbaDbTableData { Write-Message -Level SomewhatVerbose -Message "FQTN processed: $fqtn" #endregion Resolve Full Qualified Table Name - - #region Get database - # we used to do a try catch on $server.Databases if $server.ServerType -eq 'SqlAzureDatabase' here - # but it seems this was fixed in the newest SMO - try { - # This works for both onprem and azure -- using a hash only works for onprem - $databaseObject = $server.Databases | Where-Object Name -eq $databaseName - #endregion Get database - - #region Prepare database and bulk operations - if ($null -eq $databaseObject) { - Stop-Function -Message "Database $databaseName does not exist." -Target $SqlInstance - return - } - - $databaseObject.Tables.Refresh() - if ($schemaName -notin $databaseObject.Schemas.Name) { - Stop-Function -Message "Schema $schemaName does not exist." - return + #region Test if table exists + if ($tableName.StartsWith('#')) { + try { + Write-Message -Level Verbose -Message "The table $tableName should be in tempdb and we try to find it." + $null = $server.ConnectionContext.ExecuteScalar("SELECT TOP(1) 1 FROM [$tableName]") + $tableExists = $true + } catch { + $tableExists = $false } - - if ($tableName.StartsWith('#')) { - try { - Write-Message -Level Verbose -Message "The table $tableName should be in tempdb and we try to find it." - $null = $databaseObject.Query("SELECT TOP(1) 1 FROM [$tableName]") - $tableExists = $true - } catch { - $tableExists = $false - } - } else { - $targetTable = $databaseObject.Tables | Where-Object { $_.Name -eq $tableName -and $_.Schema -eq $schemaName } - $tableExists = $targetTable.Count -eq 1 + } else { + # We don't use SMO here because it does not work for Azure SQL Database connected with AccessToken. + try { + $null = $server.ConnectionContext.ExecuteScalar("SELECT TOP(1) 1 FROM $fqtn") + $tableExists = $true + } catch { + $tableExists = $false } - } catch { - Stop-Function -Message "Failure" -ErrorRecord $_ -Continue } if ((-not $tableExists) -and (-not $AutoCreateTable)) { Stop-Function -Message "Table does not exist and automatic creation of the table has not been selected. Specify the '-AutoCreateTable'-parameter to generate a suitable table." return } + #endregion Test if table exists $bulkCopyOptions = 0 $options = "TableLock", "CheckConstraints", "FireTriggers", "KeepIdentity", "KeepNulls", "Default" diff --git a/tests/Backup-DbaDatabase.Tests.ps1 b/tests/Backup-DbaDatabase.Tests.ps1 index 26889a9db6f9..997f4cf0fc20 100644 --- a/tests/Backup-DbaDatabase.Tests.ps1 +++ b/tests/Backup-DbaDatabase.Tests.ps1 @@ -50,7 +50,7 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } Context "No database found to backup should raise warning and null output" { - $results = Backup-DbaDatabase -SqlInstance $script:instance1 -BackupDirectory $DestBackupDir -Database AliceDoesntDBHereAnyMore -WarningVariable warnvar + $results = Backup-DbaDatabase -SqlInstance $script:instance1 -BackupDirectory $DestBackupDir -Database AliceDoesntDBHereAnyMore -WarningVariable warnvar 3> $null It "Should not return object" { $results | Should -Be $null } @@ -116,10 +116,9 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $warnvar | Should -BeLike "*$MissingPath*" } # $MissingPathTrailing has a trailing slash but we normalize the path before doing the actual backup - $results = Backup-DbaDatabase -SqlInstance $script:instance1 -Database master -BackupDirectory $MissingPathTrailing -WarningVariable warnvar -BuildPath + $results = Backup-DbaDatabase -SqlInstance $script:instance1 -Database master -BackupDirectory $MissingPathTrailing -BuildPath It "Should have backed up to $MissingPath" { $results.BackupFolder | Should -Be "$MissingPath" - $results.Path | Should -Not -BeLike '*\\*' } } @@ -246,9 +245,9 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } Context "Test Backup-DbaDatabase can take pipe input" { - $results = Get-DbaDatabase -SqlInstance $script:instance1 -Database master | Backup-DbaDatabase -confirm:$false -WarningVariable warnvar + $results = Get-DbaDatabase -SqlInstance $script:instance1 -Database master | Backup-DbaDatabase -confirm:$false -WarningVariable warnvar 3> $null It "Should not warn" { - '' -eq $warnvar | Should -Be $True + $warnvar | Should -BeNullOrEmpty } It "Should Complete Successfully" { $results.BackupComplete | Should -Be $true diff --git a/tests/Backup-DbaDbCertificate.Tests.ps1 b/tests/Backup-DbaDbCertificate.Tests.ps1 index 85e62dd1cf7a..445de01875f9 100644 --- a/tests/Backup-DbaDbCertificate.Tests.ps1 +++ b/tests/Backup-DbaDbCertificate.Tests.ps1 @@ -43,7 +43,7 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { It "warns the caller if the cert cannot be found" { $invalidDBCertName = "dbatoolscli_invalidCertName" $invalidDBCertName2 = "dbatoolscli_invalidCertName2" - $results = Backup-DbaDbCertificate -SqlInstance $script:instance1 -Certificate $invalidDBCertName, $invalidDBCertName2, $cert2.Name -Database $db1Name -EncryptionPassword $pw -DecryptionPassword $pw -WarningVariable warnVariable + $results = Backup-DbaDbCertificate -SqlInstance $script:instance1 -Certificate $invalidDBCertName, $invalidDBCertName2, $cert2.Name -Database $db1Name -EncryptionPassword $pw -DecryptionPassword $pw -WarningVariable warnVariable 3> $null $null = Get-ChildItem -Path $results.Path -ErrorAction Ignore | Remove-Item -Confirm:$false -ErrorAction Ignore #$results.Certificate | Should -Be $cert2.Name $warnVariable | Should -BeLike "*Database certificate(s) * not found*" diff --git a/tests/Connect-DbaInstance.Tests.ps1 b/tests/Connect-DbaInstance.Tests.ps1 index 4d45c5ce6aec..7c066e83dbfe 100644 --- a/tests/Connect-DbaInstance.Tests.ps1 +++ b/tests/Connect-DbaInstance.Tests.ps1 @@ -195,9 +195,9 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } It "clones when using parameter StatementTimeout" { - $serverClone = Connect-DbaInstance -SqlInstance $server -StatementTimeout 0 + $serverClone = Connect-DbaInstance -SqlInstance $server -StatementTimeout 123 $server.ConnectionContext.StatementTimeout | Should -Be (Get-DbatoolsConfigValue -FullName 'sql.execution.timeout') - $serverClone.ConnectionContext.StatementTimeout | Should -Be 0 + $serverClone.ConnectionContext.StatementTimeout | Should -Be 123 } It "clones when using parameter DedicatedAdminConnection" { diff --git a/tests/ConvertTo-DbaDataTable.Tests.ps1 b/tests/ConvertTo-DbaDataTable.Tests.ps1 index 9c396c2a382a..4d1fb2a3a34f 100644 --- a/tests/ConvertTo-DbaDataTable.Tests.ps1 +++ b/tests/ConvertTo-DbaDataTable.Tests.ps1 @@ -267,8 +267,8 @@ Describe "Testing input parameters" { } It "Suppresses warning messages when Silent is used" { - $null = ConvertTo-DbaDataTable -InputObject (returnnull) -IgnoreNull -EnableException -WarningVariable warn -WarningAction SilentlyContinue - $warn.message -eq $null | Should -Be $true + $null = ConvertTo-DbaDataTable -InputObject (returnnull) -IgnoreNull -EnableException -WarningVariable warn -WarningAction SilentlyContinue 3> $null + $warn | Should -BeNullOrEmpty } } diff --git a/tests/Copy-DbaAgentAlert.Tests.ps1 b/tests/Copy-DbaAgentAlert.Tests.ps1 index bea925fb23f1..b4361ae41f33 100644 --- a/tests/Copy-DbaAgentAlert.Tests.ps1 +++ b/tests/Copy-DbaAgentAlert.Tests.ps1 @@ -63,7 +63,7 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { } It "Skips alerts where destination is missing the operator" { - $results = Copy-DbaAgentAlert -Source $script:instance2 -Destination $script:instance3 -Alert $alert2 -WarningVariable warningInfo -WarningAction SilentlyContinue + $results = Copy-DbaAgentAlert -Source $script:instance2 -Destination $script:instance3 -Alert $alert2 -WarningAction SilentlyContinue $results.Status -eq 'Skipped', 'Skipped' } diff --git a/tests/Copy-DbaBackupDevice.Tests.ps1 b/tests/Copy-DbaBackupDevice.Tests.ps1 index 786e9f8ae736..eac4f6ad8ab9 100644 --- a/tests/Copy-DbaBackupDevice.Tests.ps1 +++ b/tests/Copy-DbaBackupDevice.Tests.ps1 @@ -34,10 +34,10 @@ if (-not $env:appveyor) { } } - $results = Copy-DbaBackupDevice -Source $script:instance1 -Destination $script:instance2 -WarningVariable warn -WarningAction SilentlyContinue + $results = Copy-DbaBackupDevice -Source $script:instance1 -Destination $script:instance2 -WarningVariable warn -WarningAction SilentlyContinue 3> $null if ($warn) { It "warns if it has a problem moving (issue for local to local)" { - $warn -match "backup device to destination" | Should Be $true + $warn | Should -Match "backup device to destination" } } else { It "should report success" { diff --git a/tests/Copy-DbaCredential.Tests.ps1 b/tests/Copy-DbaCredential.Tests.ps1 index d99f72da41c8..4cdaaa52a041 100644 --- a/tests/Copy-DbaCredential.Tests.ps1 +++ b/tests/Copy-DbaCredential.Tests.ps1 @@ -128,7 +128,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { It -Skip:(-not $cryptoProvider) "check warning message if crypto provider is not configured/enabled on destination" { Remove-DbaCredential -SqlInstance $instance3 -Credential dbatoolsci_thor_crypto -Confirm:$false $instance3.Query("ALTER CRYPTOGRAPHIC PROVIDER $cryptoProvider DISABLE") - $results = Copy-DbaCredential -Source $instance2 -Destination $instance3 -Name dbatoolsci_thor_crypto -WarningVariable warnings + $results = Copy-DbaCredential -Source $instance2 -Destination $instance3 -Name dbatoolsci_thor_crypto $instance3.Query("ALTER CRYPTOGRAPHIC PROVIDER $cryptoProvider ENABLE") $results.Status | Should Be Failed $results.Notes | Should -Match "The cryptographic provider $cryptoProvider needs to be configured and enabled on" diff --git a/tests/Copy-DbaDatabase.Tests.ps1 b/tests/Copy-DbaDatabase.Tests.ps1 index 32254a67cd2b..3a071e937a47 100644 --- a/tests/Copy-DbaDatabase.Tests.ps1 +++ b/tests/Copy-DbaDatabase.Tests.ps1 @@ -182,9 +182,8 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { } It "Should warn if trying to rename and prefix" { - $results = Copy-DbaDatabase -Source $script:instance2 -Destination $script:instance3 -Database $backuprestoredb -BackupRestore -SharedPath $NetworkPath -NewName $newname -prefix pre -WarningVariable warnvar + $null = Copy-DbaDatabase -Source $script:instance2 -Destination $script:instance3 -Database $backuprestoredb -BackupRestore -SharedPath $NetworkPath -NewName $newname -prefix pre -WarningVariable warnvar 3> $null $warnvar | Should -BeLike "*NewName and Prefix are exclusive options, cannot specify both" - } It "Should prefix databasename and files" { @@ -219,9 +218,8 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { $null = Restore-DbaDatabase -SqlInstance $script:instance2 -path $script:appveyorlabrepo\RestoreTimeClean2016 -useDestinationDefaultDirectories It "Should warn and exit if newname and >1 db specified" { - $prefix = "copy$(Get-Random)" - $results = Copy-DbaDatabase -Source $script:instance2 -Destination $script:instance3 -Database $backuprestoredb, RestoreTimeClean -DetachAttach -Reattach -NewName warn -WarningVariable warnvar - $Warnvar | Should -BeLike "*Cannot use NewName when copying multiple databases" + $null = Copy-DbaDatabase -Source $script:instance2 -Destination $script:instance3 -Database $backuprestoredb, RestoreTimeClean -DetachAttach -Reattach -NewName warn -WarningVariable warnvar 3> $null + $warnvar | Should -BeLike "*Cannot use NewName when copying multiple databases" } } diff --git a/tests/Copy-DbaDbTableData.Tests.ps1 b/tests/Copy-DbaDbTableData.Tests.ps1 index 712b6e949d21..d864cfb16f13 100644 --- a/tests/Copy-DbaDbTableData.Tests.ps1 +++ b/tests/Copy-DbaDbTableData.Tests.ps1 @@ -112,7 +112,7 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } It "Should warn if the destinaton table doesn't exist" { - $result = Copy-DbaDbTableData -SqlInstance $script:instance1 -Database tempdb -Table dbatoolsci_example -DestinationTable dbatoolsci_doesntexist -WarningVariable tablewarning + $result = Copy-DbaDbTableData -SqlInstance $script:instance1 -Database tempdb -Table dbatoolsci_example -DestinationTable dbatoolsci_doesntexist -WarningVariable tablewarning 3> $null $result | Should -Be $null $tablewarning | Should -Match Auto } @@ -123,7 +123,7 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } It "Should warn if the source database doesn't exist" { - $result = Copy-DbaDbTableData -SqlInstance $script:instance2 -Database tempdb_invalid -Table dbatoolsci_example -DestinationTable dbatoolsci_doesntexist -WarningVariable tablewarning + $result = Copy-DbaDbTableData -SqlInstance $script:instance2 -Database tempdb_invalid -Table dbatoolsci_example -DestinationTable dbatoolsci_doesntexist -WarningVariable tablewarning 3> $null $result | Should -Be $null $tablewarning | Should -Match "cannot open database" } diff --git a/tests/Copy-DbaDbViewData.Tests.ps1 b/tests/Copy-DbaDbViewData.Tests.ps1 index a5b2b7c559eb..9e4e6418149b 100644 --- a/tests/Copy-DbaDbViewData.Tests.ps1 +++ b/tests/Copy-DbaDbViewData.Tests.ps1 @@ -114,13 +114,13 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } It "Should warn and return nothing if Source and Destination are same" { - $result = Copy-DbaDbViewData -SqlInstance $script:instance1 -Database tempdb -View dbatoolsci_view_example -Truncate -WarningVariable tablewarning + $result = Copy-DbaDbViewData -SqlInstance $script:instance1 -Database tempdb -View dbatoolsci_view_example -Truncate -WarningVariable tablewarning 3> $null $result | Should -Be $null $tablewarning | Should -match "Cannot copy dbatoolsci_view_example into itself" } It "Should warn if the destination table doesn't exist" { - $result = Copy-DbaDbViewData -SqlInstance $script:instance1 -Database tempdb -View tempdb.dbo.dbatoolsci_view_example -DestinationTable dbatoolsci_view_does_not_exist -WarningVariable tablewarning + $result = Copy-DbaDbViewData -SqlInstance $script:instance1 -Database tempdb -View tempdb.dbo.dbatoolsci_view_example -DestinationTable dbatoolsci_view_does_not_exist -WarningVariable tablewarning 3> $null $result | Should -Be $null $tablewarning | Should -match Auto } @@ -131,7 +131,7 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } It "Should warn if the source database doesn't exist" { - $result = Copy-DbaDbViewData -SqlInstance $script:instance2 -Database tempdb_invalid -View dbatoolsci_view_example -DestinationTable dbatoolsci_doesntexist -WarningVariable tablewarning + $result = Copy-DbaDbViewData -SqlInstance $script:instance2 -Database tempdb_invalid -View dbatoolsci_view_example -DestinationTable dbatoolsci_doesntexist -WarningVariable tablewarning 3> $null $result | Should -Be $null $tablewarning | Should -match "Failure" } diff --git a/tests/Copy-DbaInstanceTrigger.Tests.ps1 b/tests/Copy-DbaInstanceTrigger.Tests.ps1 index 56635d15309b..91e5839e7ff8 100644 --- a/tests/Copy-DbaInstanceTrigger.Tests.ps1 +++ b/tests/Copy-DbaInstanceTrigger.Tests.ps1 @@ -35,7 +35,7 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } } - $results = Copy-DbaInstanceTrigger -Source $script:instance1 -Destination $script:instance2 -WarningVariable warn -WarningAction SilentlyContinue # -ServerTrigger $triggername + $results = Copy-DbaInstanceTrigger -Source $script:instance1 -Destination $script:instance2 -WarningAction SilentlyContinue It "should report success" { $results.Status | Should Be "Successful" diff --git a/tests/Copy-DbaRegServer.Tests.ps1 b/tests/Copy-DbaRegServer.Tests.ps1 index de8c14384679..e8df0c654a14 100644 --- a/tests/Copy-DbaRegServer.Tests.ps1 +++ b/tests/Copy-DbaRegServer.Tests.ps1 @@ -44,7 +44,7 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $groupstore.Drop() } - $results = Copy-DbaRegServer -Source $script:instance2 -Destination $script:instance1 -WarningVariable warn -WarningAction SilentlyContinue -CMSGroup $group + $results = Copy-DbaRegServer -Source $script:instance2 -Destination $script:instance1 -WarningAction SilentlyContinue -CMSGroup $group It "should report success" { $results.Status | Should Be "Successful", "Successful" diff --git a/tests/Disable-DbaDbEncryption.Tests.ps1 b/tests/Disable-DbaDbEncryption.Tests.ps1 index 222484454199..79af457ac853 100644 --- a/tests/Disable-DbaDbEncryption.Tests.ps1 +++ b/tests/Disable-DbaDbEncryption.Tests.ps1 @@ -51,7 +51,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { It "should disable encryption on a database with piping" { # Give it time to finish encrypting or it'll error Start-Sleep 10 - $results = $db | Disable-DbaDbEncryption -NoEncryptionKeyDrop -WarningVariable warn + $results = $db | Disable-DbaDbEncryption -NoEncryptionKeyDrop -WarningVariable warn 3> $null $warn | Should -Be $null $results.EncryptionEnabled | Should -Be $false } @@ -59,7 +59,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $null = $db | Enable-DbaDbEncryption -EncryptorName $mastercert.Name -Force # Give it time to finish encrypting or it'll error Start-Sleep 10 - $results = Disable-DbaDbEncryption -SqlInstance $script:instance2 -Database $db.Name -WarningVariable warn + $results = Disable-DbaDbEncryption -SqlInstance $script:instance2 -Database $db.Name -WarningVariable warn 3> $null $warn | Should -Be $null $results.EncryptionEnabled | Should -Be $false } diff --git a/tests/Disable-DbaFilestream.Tests.ps1 b/tests/Disable-DbaFilestream.Tests.ps1 index 478b68b00520..826b132f1dc9 100644 --- a/tests/Disable-DbaFilestream.Tests.ps1 +++ b/tests/Disable-DbaFilestream.Tests.ps1 @@ -24,7 +24,7 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { Context "Changing FileStream Level" { $NewLevel = ($OriginalFileStream.FileStreamStateId + 1) % 3 #Move it on one, but keep it less than 4 with modulo division - $results = Set-DbaFilestream -SqlInstance $script:instance1 -FileStreamLevel $NewLevel -Force -WarningVariable warnvar -WarningAction silentlyContinue -ErrorVariable errvar -Erroraction silentlyContinue + $results = Set-DbaFilestream -SqlInstance $script:instance1 -FileStreamLevel $NewLevel -Force -WarningAction silentlyContinue -ErrorVariable errvar -Erroraction silentlyContinue It "Should have changed the FileStream Level" { $results.InstanceAccessLevel | Should be $NewLevel } diff --git a/tests/Dismount-DbaDatabase.Tests.ps1 b/tests/Dismount-DbaDatabase.Tests.ps1 index 383c9e971489..8c17a1f28115 100644 --- a/tests/Dismount-DbaDatabase.Tests.ps1 +++ b/tests/Dismount-DbaDatabase.Tests.ps1 @@ -84,7 +84,7 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { } It "Skips detachment if database is snapshotted" { - $result = Dismount-DbaDatabase -SqlInstance $script:instance3 -Database $db2 -Force -WarningAction SilentlyContinue -WarningVariable warn + $result = Dismount-DbaDatabase -SqlInstance $script:instance3 -Database $db2 -Force -WarningAction SilentlyContinue -WarningVariable warn 3> $null $result | Should Be $null $warn -match "snapshot" | Should Be $true $result = Get-DbaDatabase -SqlInstance $script:instance3 -Database $db2 diff --git a/tests/Export-DbaUser.Tests.ps1 b/tests/Export-DbaUser.Tests.ps1 index 7873c12cdc85..bbb0562abff9 100644 --- a/tests/Export-DbaUser.Tests.ps1 +++ b/tests/Export-DbaUser.Tests.ps1 @@ -27,21 +27,42 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { $user2 = "dbatoolsci_exportdbauser_user2" $table = "dbatoolsci_exportdbauser_table" $role = "dbatoolsci_exportdbauser_role" + + # For Dependencies elimination test + $login01 = "dbatoolsci_exportdbauser_login01" + $login02 = "dbatoolsci_exportdbauser_login02" + $user01 = "dbatoolsci_exportdbauser_user01" + $user02 = "dbatoolsci_exportdbauser_user02" + $role01 = "dbatoolsci_exportdbauser_role01" + $role02 = "dbatoolsci_exportdbauser_role02" + $role03 = "dbatoolsci_exportdbauser_role03" + $server = Connect-DbaInstance -SqlInstance $script:instance1 $null = $server.Query("CREATE DATABASE [$dbname]") $securePassword = $(ConvertTo-SecureString -String "GoodPass1234!" -AsPlainText -Force) $null = New-DbaLogin -SqlInstance $script:instance1 -Login $login -Password $securePassword $null = New-DbaLogin -SqlInstance $script:instance1 -Login $login2 -Password $securePassword + $null = New-DbaLogin -SqlInstance $script:instance1 -Login $login01 -Password $securePassword + $null = New-DbaLogin -SqlInstance $script:instance1 -Login $login02 -Password $securePassword $db = Get-DbaDatabase -SqlInstance $script:instance1 -Database $dbname $null = $db.Query("CREATE USER [$user] FOR LOGIN [$login]") $null = $db.Query("CREATE USER [$user2] FOR LOGIN [$login2]") + $null = $db.Query("CREATE USER [$user01] FOR LOGIN [$login01]") + $null = $db.Query("CREATE USER [$user02] FOR LOGIN [$login02]") $null = $db.Query("CREATE ROLE [$role]") + $null = $db.Query("CREATE ROLE [$role01]") + $null = $db.Query("CREATE ROLE [$role02]") + $null = $db.Query("CREATE ROLE [$role03]") $null = $db.Query("CREATE TABLE $table (C1 INT);") $null = $db.Query("GRANT SELECT ON OBJECT::$table TO [$user];") $null = $db.Query("EXEC sp_addrolemember '$role', '$user';") + $null = $db.Query("EXEC sp_addrolemember '$role01', '$user01';") + $null = $db.Query("EXEC sp_addrolemember '$role02', '$user01';") + $null = $db.Query("EXEC sp_addrolemember '$role02', '$user02';") + $null = $db.Query("EXEC sp_addrolemember '$role03', '$user02';") $null = $db.Query("GRANT SELECT ON OBJECT::$table TO [$user2];") } catch { } # No idea why appveyor can't handle this } @@ -99,8 +120,9 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "Check if one output file per user was created" { $null = Export-DbaUser -SqlInstance $script:instance1 -Database $dbname -Path $outputPath - It "Exports two files to the path" { - (Get-ChildItem $outputPath).Count | Should Be 2 + It "Exports files to the path" { + $userCount = (Get-DbaDbUser -SqlInstance $script:instance1 -Database $dbname | Where-Object { $_.Name -notin @("dbo", "guest", "sys", "INFORMATION_SCHEMA") } | Measure-Object).Count + (Get-ChildItem $outputPath).Count | Should Be $userCount } It "Exported file name contains username '$user'" { Get-ChildItem $outputPath | Where-Object Name -like ('*' + $User + '*') | Should BeTrue @@ -109,4 +131,34 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Get-ChildItem $outputPath | Where-Object Name -like ('*' + $User2 + '*') | Should BeTrue } } + + Context "Check if the output scripts were self-contained" { + # Clean up the output folder + Remove-Item -Path $outputPath -Recurse -ErrorAction SilentlyContinue + $null = Export-DbaUser -SqlInstance $script:instance1 -Database $dbname -Path $outputPath + + It "Contains the CREATE ROLE and ALTER ROLE statements for its own roles" { + Get-ChildItem $outputPath | Where-Object Name -like ('*' + $user01 + '*') | ForEach-Object { + $content = Get-Content -Path $_.FullName -Raw + $content | Should BeLike "*CREATE ROLE [[]$role01]*" + $content | Should BeLike "*CREATE ROLE [[]$role02]*" + $content | Should Not BeLike "*CREATE ROLE [[]$role03]*" + + $content | Should BeLike "*ALTER ROLE [[]$role01] ADD MEMBER [[]$user01]*" + $content | Should BeLike "*ALTER ROLE [[]$role02] ADD MEMBER [[]$user01]*" + $content | Should Not BeLike "*ALTER ROLE [[]$role03]*" + } + + Get-ChildItem $outputPath | Where-Object Name -like ('*' + $user02 + '*') | ForEach-Object { + $content = Get-Content -Path $_.FullName -Raw + $content | Should BeLike "*CREATE ROLE [[]$role02]*" + $content | Should BeLike "*CREATE ROLE [[]$role03]*" + $content | Should Not BeLike "*CREATE ROLE [[]$role01]*" + + $content | Should BeLike "*ALTER ROLE [[]$role02] ADD MEMBER [[]$user02]*" + $content | Should BeLike "*ALTER ROLE [[]$role03] ADD MEMBER [[]$user02]*" + $content | Should Not BeLike "*ALTER ROLE [[]$role01]*" + } + } + } } \ No newline at end of file diff --git a/tests/Get-DbaBackupInformation.Tests.ps1 b/tests/Get-DbaBackupInformation.Tests.ps1 index d77c402ed2c2..6e1ba343d555 100644 --- a/tests/Get-DbaBackupInformation.Tests.ps1 +++ b/tests/Get-DbaBackupInformation.Tests.ps1 @@ -130,9 +130,9 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { It "Should be 0 log backups" { ($resultsSanLog | Where-Object {$_.Type -eq 'Transaction Log'}).count | Should be 0 } - $ResultsSanLog = Get-DbaBackupInformation -SqlInstance $script:instance1 -Path $DestBackupDirOla -IgnoreLogBackup -WarningVariable warnvar -WarningAction SilentlyContinue + $ResultsSanLog = Get-DbaBackupInformation -SqlInstance $script:instance1 -Path $DestBackupDirOla -IgnoreLogBackup -WarningVariable warnvar -WarningAction SilentlyContinue 3> $null It "Should Warn if IgnoreLogBackup without MaintenanceSolution" { - ($WarnVar -match "IgnoreLogBackup can only by used with MaintenanceSolution. Will not be used") | Should Be $True + $warnVar | Should -Match "IgnoreLogBackup can only by used with MaintenanceSolution. Will not be used" } It "Should ignore IgnoreLogBackup and return 3 backups" { $resultsSanLog.count | Should Be 3 diff --git a/tests/Get-DbaDbAsymmetricKey.Tests.ps1 b/tests/Get-DbaDbAsymmetricKey.Tests.ps1 index 4c02b7890589..fdbca45985fa 100644 --- a/tests/Get-DbaDbAsymmetricKey.Tests.ps1 +++ b/tests/Get-DbaDbAsymmetricKey.Tests.ps1 @@ -24,7 +24,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $tPassword = ConvertTo-SecureString "ThisIsThePassword1" -AsPlainText -Force New-DbaDbMasterKey -SqlInstance $script:instance2 -Database $database -SecurePassword $tPassword -confirm:$false New-DbaDbUser -SqlInstance $script:instance2 -Database $database -UserName $dbuser - $key = New-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Database $database -Name $keyname -Owner keyowner -Algorithm $algorithm -WarningVariable warnvar + $null = New-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Database $database -Name $keyname -Owner keyowner -Algorithm $algorithm -WarningVariable warnvar $results = Get-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Name $keyname -Database $database It "Should Create new key in $database called $keyname" { $warnvar | Should -BeNullOrEmpty @@ -42,7 +42,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $pipeResults | Should -HaveCount 1 } - $key2 = New-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Database $database -Name $keyname2 -Owner keyowner -Algorithm $algorithm -WarningVariable warnvar + $null = New-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Database $database -Name $keyname2 -Owner keyowner -Algorithm $algorithm -WarningVariable warnvar $multiResults = Get-DbaDatabase -SqlInstance $script:instance2 -Database $database | Get-DbaDbAsymmetricKey It "Should return 2 keys" { $multiResults | Should -HaveCount 2 diff --git a/tests/Get-DbaDbBackupHistory.Tests.ps1 b/tests/Get-DbaDbBackupHistory.Tests.ps1 index 2545a4ec5dbe..497bcc6e68bf 100644 --- a/tests/Get-DbaDbBackupHistory.Tests.ps1 +++ b/tests/Get-DbaDbBackupHistory.Tests.ps1 @@ -172,7 +172,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { } It "Invalid type for -Since" { - $results = Get-DbaDbBackupHistory -SqlInstance $script:instance1 -Database $dbname -Since "-" -WarningVariable warning + $results = Get-DbaDbBackupHistory -SqlInstance $script:instance1 -Database $dbname -Since "-" -WarningVariable warning 3> $null $results | Should -BeNullOrEmpty $warning | Should -BeLike "*-Since must be either a DateTime or TimeSpan object*" } diff --git a/tests/Get-DbaDbCompatibility.Tests.ps1 b/tests/Get-DbaDbCompatibility.Tests.ps1 index fc2b37b404b4..237d02b07b26 100644 --- a/tests/Get-DbaDbCompatibility.Tests.ps1 +++ b/tests/Get-DbaDbCompatibility.Tests.ps1 @@ -14,14 +14,18 @@ Describe "$CommandName Unit Tests" -Tag 'UnitTests' { } Describe "$commandname Integration Tests" -Tags "IntegrationTests" { + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $script:instance1 + $compatibilityLevel = $server.Databases['master'].CompatibilityLevel + } Context "Gets compatibility for multiple databases" { $results = Get-DbaDbCompatibility -SqlInstance $script:instance1 It "Gets results" { $results | Should Not Be $null } Foreach ($row in $results) { - It "Should return Compatiblity level of Version100 for $($row.database)" { - $row.Compatibility | Should Be "Version100" + It "Should return correct compatibility level for $($row.database)" { + $row.Compatibility | Should Be $compatibilityLevel $row.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $script:instance1 -Database $row.Database).Id } } @@ -32,8 +36,8 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { It "Gets results" { $results | Should Not Be $null } - It "Should return Compatiblity level of Version100 for $($results.database)" { - $results.Compatibility | Should Be "Version100" + It "Should return correct compatibility level for $($results.database)" { + $results.Compatibility | Should Be $compatibilityLevel $results.DatabaseId | Should -Be (Get-DbaDatabase -SqlInstance $script:instance1 -Database master).Id } } diff --git a/tests/Get-DbaDbDetachedFileInfo.Tests.ps1 b/tests/Get-DbaDbDetachedFileInfo.Tests.ps1 index 04febf30264a..a079fc59a793 100644 --- a/tests/Get-DbaDbDetachedFileInfo.Tests.ps1 +++ b/tests/Get-DbaDbDetachedFileInfo.Tests.ps1 @@ -16,6 +16,7 @@ Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { BeforeAll { $server = Connect-DbaInstance -SqlInstance $script:instance2 + $versionName = $server.GetSqlServerVersionName() $random = Get-Random $dbname = "dbatoolsci_detatch_$random" $server.Query("CREATE DATABASE $dbname") @@ -38,8 +39,8 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { It "Should be created database" { $results.name | Should Be $dbname } - It "Should be 2016" { - $results.version | Should Be 'SQL Server 2016' + It "Should be the correct version" { + $results.version | Should Be $versionName } It "Should have Data files" { $results.DataFiles | Should Not Be $null diff --git a/tests/Get-DbaDbRestoreHistory.Tests.ps1 b/tests/Get-DbaDbRestoreHistory.Tests.ps1 index c8555399bf59..5e845e80a27a 100644 --- a/tests/Get-DbaDbRestoreHistory.Tests.ps1 +++ b/tests/Get-DbaDbRestoreHistory.Tests.ps1 @@ -16,10 +16,6 @@ Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Describe "$commandname Integration Tests" -Tags "IntegrationTests" { BeforeAll { - $DestBackupDir = 'C:\Temp\backups' - if (-Not(Test-Path $DestBackupDir)) { - New-Item -Type Container -Path $DestBackupDir - } $random = Get-Random $dbname1 = "dbatoolsci_restorehistory1_$random" $dbname2 = "dbatoolsci_restorehistory2_$random" diff --git a/tests/Get-DbaDbSharePoint.Tests.ps1 b/tests/Get-DbaDbSharePoint.Tests.ps1 index 6209b6ed2ab7..f81ae30229b9 100644 --- a/tests/Get-DbaDbSharePoint.Tests.ps1 +++ b/tests/Get-DbaDbSharePoint.Tests.ps1 @@ -15,21 +15,39 @@ Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Describe "$commandname Integration Tests" -Tag "IntegrationTests" { BeforeAll { + $skip = $false $spdb = 'SharePoint_Admin_7c0c491d0e6f43858f75afa5399d49ab', 'WSS_Logging', 'SecureStoreService_20e1764876504335a6d8dd0b1937f4bf', 'DefaultWebApplicationDB', 'SharePoint_Config_4c524cb90be44c6f906290fe3e34f2e0', 'DefaultPowerPivotServiceApplicationDB-5b638361-c6fc-4ad9-b8ba-d05e63e48ac6', 'SharePoint_Config_4c524cb90be44c6f906290fe3e34f2e0' - Get-DbaProcess -SqlInstance $script:instance3 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue + Get-DbaProcess -SqlInstance $script:instance2 -Program 'dbatools PowerShell module - dbatools.io' | Stop-DbaProcess -WarningAction SilentlyContinue $server = Connect-DbaInstance -SqlInstance $script:instance2 foreach ($db in $spdb) { try { $null = $server.Query("Create Database [$db]") } catch { continue } } + # Andreas Jordan: We should try to get a backup working again or even better just a sql script to set this up. # This takes a long time but I cannot figure out why every backup of this db is malformed $bacpac = "$script:appveyorlabrepo\bacpac\sharepoint_config.bacpac" - $sqlpackage = (Get-Command sqlpackage -ErrorAction Ignore).Source - if (-not $sqlpackage) { - $sqlpackage = Join-DbaPath -Path (Split-Path -Path (Get-Module dbatools*library).Path) -ChildPath lib, sqlpackage, windows, sqlpackage.exe + if (Test-Path -Path $bacpac) { + $sqlpackage = (Get-Command sqlpackage -ErrorAction Ignore).Source + if (-not $sqlpackage) { + $libraryPath = Get-DbatoolsLibraryPath + if ($libraryPath -match 'desktop$') { + $sqlpackage = Join-DbaPath -Path (Get-DbatoolsLibraryPath) -ChildPath lib, sqlpackage.exe + } elseif ($isWindows) { + $sqlpackage = Join-DbaPath -Path (Get-DbatoolsLibraryPath) -ChildPath lib, win, sqlpackage.exe + } else { + # Not implemented + } + } + # On PowerShell 5.1 on Windows Server 2022, the following line throws: + # sqlpackage.exe : *** An unexpected failure occurred: Could not load type 'Microsoft.Data.Tools.Schema.Common.Telemetry.SqlPackageSource' from assembly 'Microsoft.Data.Tools.Utilities, Version=162.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. + # On PowerShell 7.4.2 on Windows Server 2022, the following line throws: + # Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified. + . $sqlpackage /Action:Import /tsn:$script:instance2 /tdn:Sharepoint_Config /sf:$bacpac /p:Storage=File + } else { + Write-Warning -Message "No bacpac found in path [$bacpac], skipping tests." + $skip = $true } - . $sqlpackage /Action:Import /tsn:$script:instance2 /tdn:Sharepoint_Config /sf:$bacpac /p:Storage=File } AfterAll { Remove-DbaDatabase -SqlInstance $script:instance2 -Database $spdb -Confirm:$false @@ -37,7 +55,7 @@ Describe "$commandname Integration Tests" -Tag "IntegrationTests" { Context "Command gets SharePoint Databases" { $results = Get-DbaDbSharePoint -SqlInstance $script:instance2 foreach ($db in $spdb) { - It "returns $db from in the SharePoint database list" { + It -Skip:$skip "returns $db from in the SharePoint database list" { $db | Should -BeIn $results.Name } } diff --git a/tests/Get-DbaDbSpace.Tests.ps1 b/tests/Get-DbaDbSpace.Tests.ps1 index 691b8a0df66e..54a7ea280b0b 100644 --- a/tests/Get-DbaDbSpace.Tests.ps1 +++ b/tests/Get-DbaDbSpace.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[]]$params = (Get-Command $CommandName).Parameters.Keys | Where-Object { $_ -notin ('whatif', 'confirm') } [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'IncludeSystemDBs', '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 + (@(Compare-Object -ReferenceObject ($knownParameters | Where-Object { $_ }) -DifferenceObject $params).Count ) | Should Be 0 } } } @@ -24,38 +24,40 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } #Skipping these tests as internals of Get-DbaDbSpace seems to be unreliable in CI Context "Gets DbSpace" { - $results = Get-DbaDbSpace -SqlInstance $script:instance2 | Where-Object {$_.Database -eq "$dbname"} - It -skip "Gets results" { - $results | Should Not Be $null + $results = Get-DbaDbSpace -SqlInstance $script:instance2 | Where-Object { $_.Database -eq "$dbname" } + It "Gets results" { + $results | Should -Not -BeNullOrEmpty } foreach ($row in $results) { - It -skip "Should retreive space for $dbname" { - $row.Database | Should Be $dbname + It "Should retreive space for $dbname" { + $row.Database | Should -Be $dbname + $row.UsedSpace | Should -Not -BeNullOrEmpty } - It -skip "Should have a physical path for $dbname" { - $row.physicalname | Should Not Be $null + It "Should have a physical path for $dbname" { + $row.physicalname | Should -Not -BeNullOrEmpty } } } #Skipping these tests as internals of Get-DbaDbSpace seems to be unreliable in CI Context "Gets DbSpace when using -Database" { $results = Get-DbaDbSpace -SqlInstance $script:instance2 -Database $dbname - It -skip "Gets results" { + It "Gets results" { $results | Should Not Be $null } Foreach ($row in $results) { - It -skip "Should retreive space for $dbname" { - $row.Database | Should Be $dbname + It "Should retreive space for $dbname" { + $row.Database | Should -Be $dbname + $row.UsedSpace | Should -Not -BeNullOrEmpty } - It -skip "Should have a physical path for $dbname" { - $row.physicalname | Should Not Be $null + It "Should have a physical path for $dbname" { + $row.physicalname | Should -Not -BeNullOrEmpty } } } Context "Gets no DbSpace for specific database when using -ExcludeDatabase" { $results = Get-DbaDbSpace -SqlInstance $script:instance2 -ExcludeDatabase $dbname It "Gets no results" { - $results.database | Should Not Contain $dbname + $results.database | Should -Not -Contain $dbname } } } \ No newline at end of file diff --git a/tests/Get-DbaLinkedServerLogin.Tests.ps1 b/tests/Get-DbaLinkedServerLogin.Tests.ps1 index 57967ad706e8..772e2e411a8a 100644 --- a/tests/Get-DbaLinkedServerLogin.Tests.ps1 +++ b/tests/Get-DbaLinkedServerLogin.Tests.ps1 @@ -66,7 +66,7 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "ensure command works" { It "Check the validation for a linked server" { - $results = Get-DbaLinkedServerLogin -SqlInstance $instance2 -LocalLogin $localLogin1Name -WarningVariable warnings + $results = Get-DbaLinkedServerLogin -SqlInstance $instance2 -LocalLogin $localLogin1Name -WarningVariable warnings 3> $null $warnings | Should -BeLike "*LinkedServer is required*" $results | Should -BeNullOrEmpty } diff --git a/tests/Get-DbaPrivilege.Tests.ps1 b/tests/Get-DbaPrivilege.Tests.ps1 index 33cb27aab7b2..86edc86304ef 100644 --- a/tests/Get-DbaPrivilege.Tests.ps1 +++ b/tests/Get-DbaPrivilege.Tests.ps1 @@ -16,7 +16,7 @@ Describe "$CommandName Unit Tests" -Tag 'UnitTests' { Describe "$commandname Integration Tests" -Tags "IntegrationTests" { Context "Gets Instance Privilege" { - $results = Get-DbaPrivilege -ComputerName $env:ComputerName -WarningVariable warn + $results = Get-DbaPrivilege -ComputerName $env:ComputerName -WarningVariable warn 3> $null It "Gets results" { $results | Should Not Be $null } diff --git a/tests/Get-DbaUserPermission.Tests.ps1 b/tests/Get-DbaUserPermission.Tests.ps1 index fb4ff78b842e..d538a993a4a3 100644 --- a/tests/Get-DbaUserPermission.Tests.ps1 +++ b/tests/Get-DbaUserPermission.Tests.ps1 @@ -53,7 +53,7 @@ exec sp_addrolemember 'userrole','bob'; $null = New-DbaDatabase -SqlInstance $script:instance1 -Name $dbName -Collation $dbCollation - $results = Get-DbaUserPermission -SqlInstance $script:instance1 -Database $dbName -WarningVariable warnvar + $results = Get-DbaUserPermission -SqlInstance $script:instance1 -Database $dbName -WarningVariable warnvar 3> $null It "Should not warn about collation conflict" { $warnvar | Should -Be $null } diff --git a/tests/Move-DbaDbFile.Tests.ps1 b/tests/Move-DbaDbFile.Tests.ps1 index 2f3f6c615346..ecbad4f15c35 100644 --- a/tests/Move-DbaDbFile.Tests.ps1 +++ b/tests/Move-DbaDbFile.Tests.ps1 @@ -34,6 +34,9 @@ Describe "$commandname Integration Tests" -Tags "IntegrationTests" { } AfterAll { $null = Remove-DbaDatabase -SqlInstance $script:instance2 -Database "dbatoolsci_MoveDbFile", "dbatoolsci_MoveDbFile_2DataFiles" -Confirm:$false + Get-Item -Path "$physicalPathFolder\moveFile" | Remove-Item -Recurse + Get-Item -Path "$physicalPathFolder\New" | Remove-Item -Recurse + Get-Item -Path "$physicalPathFolder\dbatoolsci_MoveDbFile.mdf" | Remove-Item } Context "Should output current database structure" { diff --git a/tests/New-DbaDbAsymmetricKey.Tests.ps1 b/tests/New-DbaDbAsymmetricKey.Tests.ps1 index 10fab88e90ab..6aef3095ebb0 100644 --- a/tests/New-DbaDbAsymmetricKey.Tests.ps1 +++ b/tests/New-DbaDbAsymmetricKey.Tests.ps1 @@ -36,7 +36,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { Context "Handles pre-existing key" { $keyname = 'test1' - $key = New-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Name $keyname -Database master -WarningVariable warnvar + $key = New-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Name $keyname -Database master -WarningVariable warnvar 3> $null $null = Remove-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Name $keyname -Database master -confirm:$false It "Should Warn that they key $keyname already exists" { $Warnvar | Should -BeLike '*already exists in master on*' @@ -98,14 +98,20 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $null = Remove-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Name $keyname -Database $database -confirm:$false } - Context "Create new key in $database Loaded from a keyfile" { + Context "Create new key loaded from a keyfile" { + $skip = $false $keyname = 'filekey' $dbuser = 'keyowner' $database = 'enctest' $path = "$($script:appveyorlabrepo)\keytests\keypair.snk" - $key = New-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Database $database -Name $keyname -Owner keyowner -WarningVariable warnvar -KeySourceType File -KeySource $path - $results = Get-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Name $keyname -Database $database - It "Should Create new key in master called $keyname" { + if (Test-Path -Path $path) { + $key = New-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Database $database -Name $keyname -Owner keyowner -WarningVariable warnvar -KeySourceType File -KeySource $path + $results = Get-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Name $keyname -Database $database + } else { + Write-Warning -Message "No keypair found in path [$path], skipping tests." + $skip = $true + } + It -Skip:$skip "Should Create new key in master called $keyname" { $warnvar | Should -BeNullOrEmpty $results.database | Should -Be $database $results.name | Should -Be $keyname @@ -119,7 +125,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { $dbuser = 'keyowner' $database = 'enctest' $path = "$($script:appveyorlabrepo)\keytests\keypair.bad" - $key = New-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Database $database -Name $keyname -Owner keyowner -WarningVariable warnvar -KeySourceType File -KeySource $path + $key = New-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Database $database -Name $keyname -Owner keyowner -WarningVariable warnvar -KeySourceType File -KeySource $path 3> $null $results = Get-DbaDbAsymmetricKey -SqlInstance $script:instance2 -Name $keyname -Database $database It "Should not Create new key in $database called $keyname" { $warnvar | Should -Not -BeNullOrEmpty diff --git a/tests/New-DbaDbEncryptionKey.Tests.ps1 b/tests/New-DbaDbEncryptionKey.Tests.ps1 index 65e0f6aabde7..7ed3aed5af07 100644 --- a/tests/New-DbaDbEncryptionKey.Tests.ps1 +++ b/tests/New-DbaDbEncryptionKey.Tests.ps1 @@ -95,10 +95,14 @@ Describe "$CommandName Integration Tests for Async" -Tags "IntegrationTests" { } } + # TODO: I think I need some background on this. Was the intention to create the key or not to creeate the key? + # Currently $warn is: + # [09:49:20][New-DbaDbEncryptionKey] Failed to create encryption key in random-1299050584 on localhost\sql2016 | Cannot decrypt or encrypt using the specified asymmetric key, either because it has no private key or because the password provided for the private key is incorrect. + # Will leave it skipped for now. Context "Command does not work but warns" { # this works on docker, not sure what's up It -Skip "should warn that it cant create an encryption key" { - $null = $db | New-DbaDbEncryptionKey -Force -Type AsymmetricKey -EncryptorName $masterasym.Name -WarningVariable warn + ($null = $db | New-DbaDbEncryptionKey -Force -Type AsymmetricKey -EncryptorName $masterasym.Name -WarningVariable warn) *> $null $warn | Should -Match "n order to encrypt the database encryption key with an as" } } diff --git a/tests/New-DbaDbMailAccount.Tests.ps1 b/tests/New-DbaDbMailAccount.Tests.ps1 index 9710fc9e7e90..564563392283 100644 --- a/tests/New-DbaDbMailAccount.Tests.ps1 +++ b/tests/New-DbaDbMailAccount.Tests.ps1 @@ -42,6 +42,8 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { EmailAddress = $email_address DisplayName = $display_name ReplyToAddress = $replyto_address + # MailServer is not set, because we don't want to configure the mail server on the instance. + # MailServer = $mailserver_name } $results = New-DbaDbMailAccount @splat @@ -54,12 +56,14 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { It "Should have Description of 'Mail account for email alerts' " { $results.Description | Should Be 'Mail account for email alerts' } - It "Should have EmailAddress of 'dbatoolssci@dbatools.net' " { - $results.EmailAddress | Should Be 'dbatoolssci@dbatools.net' + # TODO: If we set the variables then we should use them, don't we? + It "Should have EmailAddress of '$email_address' " { + $results.EmailAddress | Should Be $email_address } It "Should have ReplyToAddress of 'no-reply@dbatools.net' " { $results.ReplyToAddress | Should Be 'no-reply@dbatools.net' } + # Skipped, because we have not set the MailServer, because we don't want to configure the mail server on the instance. It -Skip "Should have MailServer of '[smtp.dbatools.io]' " { $results.MailServers | Should Be '[smtp.dbatools.io]' } @@ -81,6 +85,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { It "Should have ReplyToAddress of 'no-reply@dbatools.net' " { $results.ReplyToAddress | Should Be 'no-reply@dbatools.net' } + # Skipped, because we have not set the MailServer, because we don't want to configure the mail server on the instance. It -Skip "Should have MailServer of '[smtp.dbatools.io]' " { $results.MailServers | Should Be '[smtp.dbatools.io]' } diff --git a/tests/New-DbaDbUser.Tests.ps1 b/tests/New-DbaDbUser.Tests.ps1 index b854ac6f9483..d097970fdd97 100644 --- a/tests/New-DbaDbUser.Tests.ps1 +++ b/tests/New-DbaDbUser.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 = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'IncludeSystem', 'Login', 'Username', 'Password', 'DefaultSchema', 'ExternalProvider', 'Force', 'EnableException' + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Database', 'ExcludeDatabase', 'IncludeSystem', 'User', 'Login', 'SecurePassword', 'ExternalProvider', 'DefaultSchema', '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 @@ -37,7 +37,7 @@ Describe "$CommandName Integration Tests" -Tag "IntegrationTests" { It "Tries to create the user with an invalid default schema" { $results = New-DbaDbUser -SqlInstance $script:instance2 -Database $dbname -Login $userName -DefaultSchema invalidSchemaName -WarningVariable warningMessage $results | Should -BeNullOrEmpty - $warningMessage | Should -BeLike "*Invalid DefaultSchema*" + $warningMessage | Should -BeLike "*Schema * does not exist in database*" } } Context "Should create the user with login" { diff --git a/tests/Remove-DbaDbUser.Tests.ps1 b/tests/Remove-DbaDbUser.Tests.ps1 index 687c812cd692..b1ca3d55d653 100644 --- a/tests/Remove-DbaDbUser.Tests.ps1 +++ b/tests/Remove-DbaDbUser.Tests.ps1 @@ -19,7 +19,7 @@ Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { $server = Connect-DbaInstance -SqlInstance $script:instance1 $db = Get-DbaDatabase $server -Database tempdb $securePassword = ConvertTo-SecureString "password" -AsPlainText -Force - $loginTest = New-DbaLogin $server -Login dbatoolsci_remove_dba_db_user -Password $securePassword + $loginTest = New-DbaLogin $server -Login dbatoolsci_remove_dba_db_user -Password $securePassword -Force } BeforeEach { $user = New-Object Microsoft.SqlServer.Management.SMO.User($db, $loginTest.Name) diff --git a/tests/Test-DbaDbLogShipStatus.Tests.ps1 b/tests/Test-DbaDbLogShipStatus.Tests.ps1 index e65a6ea329c8..759be691e655 100644 --- a/tests/Test-DbaDbLogShipStatus.Tests.ps1 +++ b/tests/Test-DbaDbLogShipStatus.Tests.ps1 @@ -14,7 +14,15 @@ Describe "$CommandName Unit Tests" -Tags "UnitTests" { } Describe "$CommandName Integration Tests" -Tags "IntegrationTests" { - It "warns if SQL instance edition is not supported" { + BeforeAll { + $server = Connect-DbaInstance -SqlInstance $script:instance1 + $skip = $false + if ($server.Edition -notmatch 'Express') { + $skip = $true + } + } + + It -Skip:$skip "warns if SQL instance edition is not supported" { $null = Test-DbaDbLogShipStatus -SqlInstance $script:instance1 -WarningAction SilentlyContinue -WarningVariable editionwarn $editionwarn -match "Express" | Should Be $true } diff --git a/tests/manual.pester.ps1 b/tests/manual.pester.ps1 index 89d774c4e519..a9c006ade697 100644 --- a/tests/manual.pester.ps1 +++ b/tests/manual.pester.ps1 @@ -158,7 +158,7 @@ Remove-Module dbatools -ErrorAction Ignore #imports the module making sure DLL is loaded ok Import-Module "$ModuleBase\dbatools.psd1" -DisableNameChecking #imports the psm1 to be able to use internal functions in tests -Import-Module "$ModuleBase\dbatools.psm1" -DisableNameChecking +Import-Module "$ModuleBase\dbatools.psm1" -DisableNameChecking -Force $ScriptAnalyzerRulesExclude = @('PSUseOutputTypeCorrectly', 'PSAvoidUsingPlainTextForPassword', 'PSUseBOMForUnicodeEncodedFile') diff --git a/xml/dbatools.Types.ps1xml b/xml/dbatools.Types.ps1xml index 11cff0db0b7c..7ceb92e5afb6 100644 --- a/xml/dbatools.Types.ps1xml +++ b/xml/dbatools.Types.ps1xml @@ -36,54 +36,58 @@ $this.ExecuteNonQuery($Command) Query Invoke