zigford.org/the-correct-way-to-implement--whatif-and--confirm-in-a-powershell-cmdlet.md
2020-07-21 06:49:32 +10:00

50 lines
1.4 KiB
Markdown

The correct way to implement -Whatif and -Confirm in a Powershell Cmdlet
When I first learned about `[CmdLetBinding()]` to add automatic support for
`Write-Verbose` I didn't understand why -WhatIf and -Confirm were not passed
to Cmdlets used in my functions.
---
I wrote functions like this to fake it:
function Set-BadIdea {
[CmdLetBinding()]
Param(
[string]$File,
[switch]$Whatif,
[switch]$Confirm
)
Remove-Item $File -WhatIf:$WhatIf -Confirm:$Confirm
}
While this kinda works, it doesn't allow any control over where Whatif's and
confirms are used. After reading
[Implementing ShouldProccess for your functions][1] post by Joel Francsis,
I'm now able to do things like this:
function Set-GoodIdead {
[CmdLetBinding(SupportsShouldProcess)]
Param([string]$File)
If ($PSCmdlet.ShouldProcess("$File", "Get rid of junk")) {
Remove-Item $File
}
}
As I hope you can see, you could implement the `$PSCmdlet.ShouldProcess`
on any code, not just other functions that support -WhatIf or -Confirm or
-Force
Doing this will lead to more consistent behavior of functions and allow
behaviour to be more intuitive.
For a much more in depth explaination, go and check [Joel's post][1]
Tags: powershell, coding
[1]:https://vexx32.github.io/2018/11/22/Implementing-ShouldProcess/