From 7edecc836a80fc7fef0e552154aab881bc47bef2 Mon Sep 17 00:00:00 2001 From: Chrissy LeMaire Date: Sun, 5 Nov 2023 18:35:55 +0100 Subject: [PATCH] Fix non-Windows Import Errors (#9158) --- private/configurations/configuration.ps1 | 2 +- .../configurations/settings/tabexpansion.ps1 | 20 ++++- .../settings/userinteraction.ps1 | 12 --- .../validation/consolecolor.ps1 | 22 ----- private/functions/message/Write-HostColor.ps1 | 86 +------------------ public/Remove-DbaAgentJob.ps1 | 16 +--- public/Remove-DbaAgentJobStep.ps1 | 25 +----- tests/Remove-DbaAgentJob.Tests.ps1 | 2 +- tests/Remove-DbaAgentJobStep.Tests.ps1 | 2 +- 9 files changed, 24 insertions(+), 163 deletions(-) delete mode 100644 private/configurations/validation/consolecolor.ps1 diff --git a/private/configurations/configuration.ps1 b/private/configurations/configuration.ps1 index 547dca6d44..ef50ffe597 100644 --- a/private/configurations/configuration.ps1 +++ b/private/configurations/configuration.ps1 @@ -179,7 +179,7 @@ if (-not $script:dbatools_ImportFromRegistryDone) { } else { Set-DbatoolsConfig -FullName $value.FullName -Value $true -EnableException } - } else { + } elseif ($null -ne $value.Value) { Set-DbatoolsConfig -FullName $value.FullName -Value $value.Value -EnableException } } else { diff --git a/private/configurations/settings/tabexpansion.ps1 b/private/configurations/settings/tabexpansion.ps1 index 7f816167d5..3deb044baf 100644 --- a/private/configurations/settings/tabexpansion.ps1 +++ b/private/configurations/settings/tabexpansion.ps1 @@ -8,9 +8,15 @@ Set-DbatoolsConfig -FullName 'TabExpansion.Disable' -Value $false -Initialize -V # Disable Async TEPP runspace if not needed if ([Dataplat.Dbatools.TabExpansion.TabExpansionHost]::TeppAsyncDisabled -or [Dataplat.Dbatools.TabExpansion.TabExpansionHost]::TeppDisabled) { - [Dataplat.Dbatools.Runspace.RunspaceHost]::Runspaces["dbatools-teppasynccache"].Stop() + $stoptepp = [Dataplat.Dbatools.Runspace.RunspaceHost]::Runspaces["dbatools-teppasynccache"] + if ($stoptepp) { + $stoptepp.Stop() + } } else { - [Dataplat.Dbatools.Runspace.RunspaceHost]::Runspaces["dbatools-teppasynccache"].Start() + $starttepp = [Dataplat.Dbatools.Runspace.RunspaceHost]::Runspaces["dbatools-teppasynccache"] + if ($starttepp) { + $starttepp.Start() + } } } -Description 'Globally disables all TEPP functionality by dbatools' Set-DbatoolsConfig -FullName 'TabExpansion.Disable.Asynchronous' -Value $false -Initialize -Validation bool -Handler { @@ -18,9 +24,15 @@ Set-DbatoolsConfig -FullName 'TabExpansion.Disable.Asynchronous' -Value $false - # Disable Async TEPP runspace if not needed if ([Dataplat.Dbatools.TabExpansion.TabExpansionHost]::TeppAsyncDisabled -or [Dataplat.Dbatools.TabExpansion.TabExpansionHost]::TeppDisabled) { - [Dataplat.Dbatools.Runspace.RunspaceHost]::Runspaces["dbatools-teppasynccache"].Stop() + $stoptapp = [Dataplat.Dbatools.Runspace.RunspaceHost]::Runspaces["dbatools-teppasynccache"] + if ($stoptapp) { + $stoptapp.Stop() + } } else { - [Dataplat.Dbatools.Runspace.RunspaceHost]::Runspaces["dbatools-teppasynccache"].Start() + $starttapp = [Dataplat.Dbatools.Runspace.RunspaceHost]::Runspaces["dbatools-teppasynccache"] + if ($starttapp) { + $starttapp.Start() + } } } -Description 'Globally disables asynchronous TEPP updates in the background' Set-DbatoolsConfig -FullName 'TabExpansion.Disable.Synchronous' -Value $true -Initialize -Validation bool -Handler { [Dataplat.Dbatools.TabExpansion.TabExpansionHost]::TeppSyncDisabled = $args[0] } -Description 'Globally disables synchronous TEPP updates, performed whenever connecting o the server. If this is not disabled, it will only perform updates that are fast to perform, in order to minimize performance impact. This may lead to some TEPP functionality loss if asynchronous updates are disabled.' \ No newline at end of file diff --git a/private/configurations/settings/userinteraction.ps1 b/private/configurations/settings/userinteraction.ps1 index c001d3a45a..ca1657fec9 100644 --- a/private/configurations/settings/userinteraction.ps1 +++ b/private/configurations/settings/userinteraction.ps1 @@ -11,22 +11,10 @@ Set-DbatoolsConfig -Name 'message.minimuminfo' -Value 1 -Initialize -Validation Set-DbatoolsConfig -Name 'message.minimumverbose' -Value 4 -Initialize -Validation integer0to9 -Handler { [Dataplat.Dbatools.Message.MessageHost]::MinimumVerbose = $args[0] } -Description "The minimum required message level where verbose information is written." Set-DbatoolsConfig -Name 'message.minimumdebug' -Value 1 -Initialize -Validation integer0to9 -Handler { [Dataplat.Dbatools.Message.MessageHost]::MinimumDebug = $args[0] } -Description "The minimum required message level where debug information is written." -# Default color used by the "Write-Message" function in info mode -Set-DbatoolsConfig -Name 'message.infocolor' -Value 'Cyan' -Initialize -Validation consolecolor -Handler { [Dataplat.Dbatools.Message.MessageHost]::InfoColor = $args[0] } -Description "The color to use when writing text to the screen on PowerShell." -Set-DbatoolsConfig -Name 'message.developercolor' -Value 'Grey' -Initialize -Validation consolecolor -Handler { [Dataplat.Dbatools.Message.MessageHost]::DeveloperColor = $args[0] } -Description "The color to use when writing text with developer specific additional information to the screen on PowerShell." -Set-DbatoolsConfig -Name 'message.info.color.emphasis' -Value 'green' -Initialize -Validation "consolecolor" -Handler { [Dataplat.Dbatools.Message.MessageHost]::InfoColorEmphasis = $args[0] } -Description "The color to use when emphasizing written text to the screen on PowerShell." -Set-DbatoolsConfig -Name 'message.info.color.subtle' -Value 'gray' -Initialize -Validation "consolecolor" -Handler { [Dataplat.Dbatools.Message.MessageHost]::InfoColorSubtle = $args[0] } -Description "The color to use when making writing text to the screen on PowerShell appear subtle." Set-DbatoolsConfig -Name 'message.consoleoutput.disable' -Value $false -Initialize -Validation "bool" -Handler { [Dataplat.Dbatools.Message.MessageHost]::DisableVerbosity = $args[0] } -Description "Global toggle that allows disabling all regular messages to screen. Messages from '-Verbose' and '-Debug' are unaffected" Set-DbatoolsConfig -Name 'message.transform.errorqueuesize' -Value 512 -Initialize -Validation "integerpositive" -Handler { [Dataplat.Dbatools.Message.MessageHost]::TransformErrorQueueSize = $args[0] } -Description "The size of the queue for transformation errors. May be useful for advanced development, but can be ignored usually." Set-DbatoolsConfig -Name 'message.nestedlevel.decrement' -Value 0 -Initialize -Validation "integer0to9" -Handler { [Dataplat.Dbatools.Message.MessageHost]::NestedLevelDecrement = $args[0] } -Description "How many levels should be reduced per callstack depth. This makes commands less verbose, the more nested they are called" -# Messaging mode in non-critical terminations -Set-DbatoolsConfig -Name 'message.mode.default' -Value ([DbaMode]::Strict) -Initialize -Validation string -Handler { } -Description "The mode controls how some functions handle non-critical terminations by default. Strict: Write a warning | Lazy: Write a message | Report: Generate a report object" -Set-DbatoolsConfig -Name 'message.mode.lazymessagelevel' -Value 4 -Initialize -Validation integer0to9 -Handler { } -Description "At what level will the lazy message be written? (By default invisible to the user)" - -# Enable Developer mode -Set-DbatoolsConfig -Name 'developer.mode.enable' -Value $false -Initialize -Validation bool -Handler { [Dataplat.Dbatools.Message.MessageHost]::DeveloperMode = $args[0] } -Description "Developermode enables advanced logging and verbosity features. There is little benefit for enabling this as a regular user. but developers can use it to more easily troubleshoot issues." - # Message display style options Set-DbatoolsConfig -Name 'message.style.breadcrumbs' -Value $false -Initialize -Validation "bool" -Handler { [Dataplat.Dbatools.Message.MessageHost]::EnableMessageBreadcrumbs = $args[0] } -Description "Controls how messages are displayed. Enables Breadcrumb display, showing the entire callstack. Takes precedence over command name display." Set-DbatoolsConfig -Name 'message.style.functionname' -Value $true -Initialize -Validation "bool" -Handler { [Dataplat.Dbatools.Message.MessageHost]::EnableMessageDisplayCommand = $args[0] } -Description "Controls how messages are displayed. Enables command name, showing the name of the writing command. Is overwritten by enabling breadcrumbs." diff --git a/private/configurations/validation/consolecolor.ps1 b/private/configurations/validation/consolecolor.ps1 deleted file mode 100644 index f8b01621fe..0000000000 --- a/private/configurations/validation/consolecolor.ps1 +++ /dev/null @@ -1,22 +0,0 @@ -Register-DbatoolsConfigValidation -Name "consolecolor" -ScriptBlock { - param ( - $Value - ) - - $Result = New-Object PSObject -Property @{ - Success = $True - Value = $null - Message = "" - } - - try { [System.ConsoleColor]$color = $Value } - catch { - $Result.Message = "Not a console color: $Value" - $Result.Success = $False - return $Result - } - - $Result.Value = $color - - return $Result -} \ No newline at end of file diff --git a/private/functions/message/Write-HostColor.ps1 b/private/functions/message/Write-HostColor.ps1 index db706937c0..17f9302325 100644 --- a/private/functions/message/Write-HostColor.ps1 +++ b/private/functions/message/Write-HostColor.ps1 @@ -1,86 +1,4 @@ function Write-HostColor { - <# - .SYNOPSIS - Function that recognizes html-style tags to insert color into printed text. - - .DESCRIPTION - Function that recognizes html-style tags to insert color into printed text. - - Color tags should be designed to look like this: - ">Text - For example this would be a valid string: - "This message should partially be painted in red." - - This allows specifying color within strings and avoids having to piece together colored text in multiple calls to Write-Host. - Only colors that are part of the ConsoleColor enumeration can be used. Bad colors will be ignored in favor of the default color. - - .PARAMETER String - The message to write to host. - - .PARAMETER DefaultColor - Default: (Get-DbatoolsConfigValue -Name "message.infocolor") - The color to write stuff to host in when no (or bad) color-code was specified. - - .EXAMPLE - Write-HostColor -String 'This is going to be bloody red text! And this is green stuff for extra color' - - Will print the specified line in multiple colors - - .EXAMPLE - $string1 = 'This is going to be bloody red text! And this is green stuff for extra color' - $string2 = 'bloody red text! And this is green stuff for extra color' - $string3 = 'This is going to be bloody red text! And this is green stuff' - $string1, $string2, $string3 | Write-HostColor -DefaultColor "Magenta" - - Will print all three lines, respecting the color-codes, but use the color "Magenta" as default color. - - .EXAMPLE - $stringLong = @" - Dear Sirs and Madams, - - it has come to our attention that you are not sufficiently awesome! - Kindly improve your AP (awesome-ness points) by at least 50% to maintain you membership in Awesome Inc! - - You have 27 3/4 days time to meet this deadline. After this we will unfortunately be forced to rend you assunder and sacrifice your remains to the devil. - - Best regards, - Luzifer - "@ - Write-HostColor -String $stringLong - - Will print a long multiline text in its entirety while still respecting the colorcodes - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "")] - [CmdletBinding()] - param ( - [Parameter(ValueFromPipeline)] - [string[]] - $String, - - [ConsoleColor] - $DefaultColor = (Get-DbatoolsConfigValue -Name "message.infocolor") - ) - process { - foreach ($line in $String) { - foreach ($row in $line.Split("`n").Split([environment]::NewLine)) { - if ($row -notlike '***') { Write-Host -Object $row -ForegroundColor $DefaultColor } - else { - $match = ($row | Select-String '(.*?)' -AllMatches).Matches - $index = 0 - $count = 0 - - while ($count -le $match.Count) { - if ($count -lt $Match.Count) { - Write-Host -Object $match[$count].Groups[2].Value -ForegroundColor $DefaultColor -NoNewline -ErrorAction Stop - $index = $match[$count].Index + $match[$count].Length - $count++ - } else { - Write-Host -Object $row.SubString($index) -ForegroundColor $DefaultColor - $count++ - } - } - } - } - } - } + param () + process {} } \ No newline at end of file diff --git a/public/Remove-DbaAgentJob.ps1 b/public/Remove-DbaAgentJob.ps1 index c447fdd736..ba728d58ba 100644 --- a/public/Remove-DbaAgentJob.ps1 +++ b/public/Remove-DbaAgentJob.ps1 @@ -26,12 +26,6 @@ function Remove-DbaAgentJob { Specifies to keep the schedules attached to this job if they are not attached to any other job. By default the unused schedule is deleted. - .PARAMETER Mode - Default: Strict - How strict does the command take lesser issues? - Strict: Interrupt if the job specified doesn't exist. - Lazy: Silently skip over jobs that don't exist. - .PARAMETER InputObject Accepts piped input from Get-DbaAgentJob @@ -85,7 +79,6 @@ function Remove-DbaAgentJob { [object[]]$Job, [switch]$KeepHistory, [switch]$KeepUnusedSchedule, - [DbaMode]$Mode = (Get-DbatoolsConfigValue -FullName 'message.mode.default' -Fallback "Strict"), [parameter(ValueFromPipeline)] [Microsoft.SqlServer.Management.Smo.Agent.Job[]]$InputObject, [switch]$EnableException @@ -100,14 +93,7 @@ function Remove-DbaAgentJob { foreach ($j in $Job) { if ($Server.JobServer.Jobs.Name -notcontains $j) { - switch ($Mode) { - 'Lazy' { - Write-Message -Level Verbose -Message "Job $j doesn't exists on $instance." -Target $instance - } - 'Strict' { - Stop-Function -Message "Job $j doesn't exist on $instance." -Continue -ContinueLabel main -Target $instance -Category InvalidData - } - } + Stop-Function -Message "Job $j doesn't exist on $instance." -Continue -ContinueLabel main -Target $instance -Category InvalidData } $InputObject += ($Server.JobServer.Jobs | Where-Object Name -eq $j) } diff --git a/public/Remove-DbaAgentJobStep.ps1 b/public/Remove-DbaAgentJobStep.ps1 index 492f6a775d..bfb98c59e5 100644 --- a/public/Remove-DbaAgentJobStep.ps1 +++ b/public/Remove-DbaAgentJobStep.ps1 @@ -22,12 +22,6 @@ function Remove-DbaAgentJobStep { .PARAMETER StepName The name of the job step. - .PARAMETER Mode - Default: Strict - How strict does the command take lesser issues? - Strict: Interrupt if the configuration already has the same value as the one specified. - Lazy: Silently skip over instances that already have this configuration at the specified value. - .PARAMETER WhatIf If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run. @@ -82,7 +76,6 @@ function Remove-DbaAgentJobStep { [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string]$StepName, - [DbaMode]$Mode = (Get-DbatoolsConfigValue -Name 'message.mode.default' -Fallback "Strict"), [switch]$EnableException ) @@ -99,25 +92,11 @@ function Remove-DbaAgentJobStep { Write-Message -Level Verbose -Message "Processing job $j" # Check if the job exists if ($Server.JobServer.Jobs.Name -notcontains $j) { - switch ($Mode) { - 'Lazy' { - Write-Message -Level Verbose -Message "Job $j doesn't exists on $instance." -Target $instance - } - 'Strict' { - Stop-Function -Message "Job $j doesnn't exist on $instance." -Continue -ContinueLabel main -Target $instance -Category InvalidData - } - } + Stop-Function -Message "Job $j doesnn't exist on $instance." -Continue -ContinueLabel main -Target $instance -Category InvalidData } else { # Check if the job step exists if ($Server.JobServer.Jobs[$j].JobSteps.Name -notcontains $StepName) { - switch ($Mode) { - 'Lazy' { - Write-Message -Level Verbose -Message "Step $StepName doesn't exist for $job on $instance." -Target $instance - } - 'Strict' { - Stop-Function -Message "Step $StepName doesn't exist for $job on $instance." -Continue -ContinueLabel main -Target $instance -Category InvalidData - } - } + Stop-Function -Message "Step $StepName doesn't exist for $job on $instance." -Continue -ContinueLabel main -Target $instance -Category InvalidData } else { # Execute if ($PSCmdlet.ShouldProcess($instance, "Removing the job step $StepName for job $j")) { diff --git a/tests/Remove-DbaAgentJob.Tests.ps1 b/tests/Remove-DbaAgentJob.Tests.ps1 index a518401875..857938e0b3 100644 --- a/tests/Remove-DbaAgentJob.Tests.ps1 +++ b/tests/Remove-DbaAgentJob.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', 'Job', 'KeepHistory', 'KeepUnusedSchedule', 'Mode', 'InputObject', 'EnableException' + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Job', 'KeepHistory', 'KeepUnusedSchedule', '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 diff --git a/tests/Remove-DbaAgentJobStep.Tests.ps1 b/tests/Remove-DbaAgentJobStep.Tests.ps1 index d51625ca38..a210fc34dd 100644 --- a/tests/Remove-DbaAgentJobStep.Tests.ps1 +++ b/tests/Remove-DbaAgentJobStep.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', 'Job', 'StepName', 'Mode', 'EnableException' + [object[]]$knownParameters = 'SqlInstance', 'SqlCredential', 'Job', 'StepName', '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