Skip to content

Instantly share code, notes, and snippets.

@jikuja
Last active September 23, 2024 14:13
Show Gist options
  • Save jikuja/57bfbfd01f3c9ea48c55234b769a1f86 to your computer and use it in GitHub Desktop.
Save jikuja/57bfbfd01f3c9ea48c55234b769a1f86 to your computer and use it in GitHub Desktop.
PowerShell Confirms

PowershellConfirmPreference / impact

function Test-ShouldProcess {
[CmdletBinding(
SupportsShouldProcess,
ConfirmImpact = 'High'
)]
param(
[Switch]$Force
)
Write-Verbose "`$PSCmdLet: $PSCmdLet"
Write-Verbose "`$DebugPreference: $DebugPreference"
Write-Verbose "`$ConfirmPreference: $ConfirmPreference"
Write-Verbose "`$Confirm: $Confirm"
Write-Verbose "`$Confirm: $($null -eq $Confirm ? "NULL": "NONNULL")"
if ($Force -and -not $Confirm){
Write-Verbose "Changing `$ConfirmPreference"
$ConfirmPreference = 'None'
} else {
Write-Verbose "XXXX"
}
Write-Verbose "`$DebugPreference: $DebugPreference"
Write-Verbose "`$ConfirmPreference: $ConfirmPreference"
Write-Verbose "`$Confirm: $Confirm"
Write-Verbose "`$Confirm: $($null -eq $Confirm ? "NULL": "NONNULL")"
# Does this ignore $ConfirmPreference?
# The call to $PSCmdlet.ShouldProcess($file.name) checks for the -WhatIf (and -Confirm parameter) then handles it accordingly.
if ($PSCmdlet.ShouldProcess('TARGET')){
Write-Output "Some Action"
}
if ($Force -or $PSCmdlet.ShouldContinue('TARGET','OPERATION')) {
Write-Output "Some Action"
}
}
<#
> $ConfirmPreference="Low" ; Test-ShouldProcess -force -confirm
Asks confirmation for ShouldProcess
> $ConfirmPreference="High" ; Test-ShouldProcess
Asks confirmation for both
> $ConfirmPreference="High" ; Test-ShouldProcess -Force
No confirmation asked
> $ConfirmPreference="High" ; Test-ShouldProcess -Force -Confirm
Asks confirmation for ShouldProcess
If both -Confirm and -Force are used Confirmation for ShouldProcess are requested.
Still logic of `if ($Force -and -not $Confirm){` does not make any sense and will not work on strict mode
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment