Passing parameters explicitly
You can pass the -WhatIf
and -Confirm
parameters with the $WhatIfPreference
and $ConfirmPreference
variables. The following example achieves this with parameter splatting:
if($ConfirmPreference -eq 'Low') {$conf = @{Confirm = $true}}
StopService MyService -WhatIf:([bool]$WhatIfPreference.IsPresent) @conf
$WhatIfPreference.IsPresent
will be True
if the -WhatIf
switch is used on the containing function. Using the -Confirm
switch on the containing function temporarily sets $ConfirmPreference
to low
.
Passing parameters implicitly
Since the -Confirm
and -WhatIf
temporarily set the $ConfirmPreference
and $WhatIfPreference
variables automatically, is it even necessary to pass them?
Consider the example:
function ShouldTestCallee {
[cmdletBinding(SupportsShouldProcess=$true,ConfirmImpact='Medium')]
param($test)
$PSCmdlet.ShouldProcess($env:COMPUTERNAME,"Confirm?")
}
function ShouldTestCaller {
[cmdletBinding(SupportsShouldProcess=$true)]
param($test)
ShouldTestCallee
}
$ConfirmPreference = 'High'
ShouldTestCaller
ShouldTestCaller -Confirm
ShouldTestCaller
results in True
from ShouldProcess()
ShouldTestCaller -Confirm
results in an confirm prompt even though I didn't pass the switch.
Edit
@manojlds answer made me realize that my solution was always setting $ConfirmPreference
to 'Low' or 'High'. I have updated my code to only set the -Confirm
switch if the confirm preference is 'Low'.