Are You Sure You Want to Do This?
I know I've written before about adding support for -WhatIf
to your PowerShell commands. However, I'm not sure I've fully covered the related topic of -Confirm
and how it can be used to prompt the user for confirmation before executing a command. Let's remedy that today.
Here's a simple example that defines support for -WhatIf
and -Confirm
in a PowerShell function:
Function Set-Folder {
[cmdletbinding(SupportsShouldProcess)]
Param(
[Parameter(
Position = 0,
ValueFromPipeline,
ValueFromPipelineByPropertyName
)]
[Alias('pspath')]
[ValidateScript( { Test-Path $_ })]
[string]$Path = '.')
Process {
$Path = (Resolve-Path -Path $Path).ProviderPath
if ($PSCmdlet.ShouldProcess($Path)) {
#do the action
$Path.ToUpper()
}
} #Process
} #end function
You can see the parameters.
PS C:\> Get-Command Set-Folder -Syntax
Set-Folder [[-Path] <string>] [-WhatIf] [-Confirm] [<commonparameters>]
And the expected behavior.
PS C:\> Set-Folder c:\temp -WhatIf
What if: Performing the operation "Set-Folder" on target "C:\temp".
PS C:\> Set-Folder c:\temp -confirm
Confirm
Are you sure you want to perform this action?
Performing the operation "Set-Folder" on target "C:\temp".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): y
C:\TEMP
In the function I am defining my own WhatIf support using $PSCmdlet.ShouldProcess
. You have an option to use $PSCmdlet.ShouldContinue` instead, although you will get different behavior.
Function Set-Folder {
[cmdletbinding(SupportsShouldProcess)]
Param(
[Parameter(
Position = 0,
ValueFromPipeline,
ValueFromPipelineByPropertyName
)]
[Alias('pspath')]
[ValidateScript( { Test-Path $_ })]
[string]$Path = '.')
Process {
$Path = (Resolve-Path -Path $Path).ProviderPath
#ShouldContinue("query","caption")
if ($PSCmdlet.ShouldContinue("Do you want to process folder",$Path)) {
#do the action
$Path.ToUpper()
}
} #Process
} #end function
The result may not be what you expect.
PS C:\> Set-Folder c:\temp
C:\temp
Do you want to process folder
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): n
PS C:\> Set-Folder c:\temp -WhatIf
C:\temp
Do you want to process folder
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): n
PS C:\> Set-Folder c:\temp -Confirm
C:\temp
Do you want to process folder
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): n
PS C:\>
Want to read the full issue?