PowerShell Confirmation
PowerShell provides a $PSCmdlet.ShouldProcess($target, $action)
method
(and some variants) that are enabled when a function enables SupportsShouldProcess.
The behavior is affected by the $ConfirmPreference
preference variable,
the declared ConfirmImpact
level of the function, and the -WhatIf
and -Confirm
parameters.
A $PSCmdlet.ShouldContinue($target, $action)
method is provided for greater control.
See Everything you wanted to know about ShouldProcess.
function Invoke-Action
{
[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Medium')] Param(
[psobject] $Target
)
if($PSCmdlet.ShouldProcess("$Target", 'invoke action')) { <# perform action #> }
}
$ConfirmPreference = 'High'
Invoke-Action
# (ShouldProcess returns true)
Invoke-Action -WhatIf
# What if: Performing the operation "invoke action" on target "Target".
# (ShouldProcess returns false)
Invoke-Action -Confirm
# Confirm
# Are you sure you want to perform this action?
# Performing the operation "show" on target "prompt".
# [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
ShouldProcess()
return value
- If
-WhatIf
is enabled,ShouldProcess()
will write the intended action to the host and return false. - If
-Confirm
is enabled,ShouldProcess()
will prompt. - If
$ConfirmPreference
orConfirmImpact
isNone
,ShouldProcess()
will return true. - If the function
ConfirmImpact
isHigh
,ShouldProcess()
will always prompt. - If
$ConfirmPreference
is higher thanConfirmImpact
,ShouldProcess()
will return true. ShouldProcess()
will prompt otherwise.
level$ConfirmPreference →ConfirmImpact ↓ |
Low | Medium | High | None |
---|---|---|---|---|
None | True | True | True | True |
Low | prompt | True | True | True |
Medium | prompt | prompt | True | True |
High | prompt | prompt | prompt | True |