I have a PowerShell script cmdlet that supports the -WhatIf
& -Confirm
parameters.
It does this by calling the $PSCmdlet.Should
Here is a complete solution based on @Rynant and @Shay Levy's answers:
function Stop-CompanyXyzServices
{
[CmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Medium')]
Param(
[Parameter(
Position=0,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true
)]
[string]$Name
)
process
{
if($PSCmdlet.ShouldProcess($env:COMPUTERNAME,"Stop XYZ services '$Name'")){
ActualCmdletProcess
}
if([bool]$WhatIfPreference.IsPresent){
ActualCmdletProcess
}
}
}
function ActualCmdletProcess{
# add here the actual logic of your cmdlet, and any call to other cmdlets
Stop-Service $name -WhatIf:([bool]$WhatIfPreference.IsPresent) -Confirm:("Low","Medium" -contains $ConfirmPreference)
}
We have to see if -WhatIf
is passed separately as well so that the whatif can be passed on to the individual cmdlets. ActualCmdletProcess
is basically a refactoring so that you don't call the same set of commands again just for the WhatIf
. Hope this helps someone.