My Technical Notes

Wednesday, 8 February 2017

PowerShell: Computing `$Confirm` from within a Function

There seems no way of getting the `$Confirm` flag from within a function. Also, it is not as easy as checking `$PSBoundParameters`, because if, for example, function `A` called `B`, but you specified `-Confirm` when calling `A`, then, despite `B` not having had the flag specified, it will work as though you specified the `-Confirm` specified because of how certain special parameters are passed down automatically.

The following `Test-Confirm` function returns a `boolean` value of `Confirm`:


Function Test-Confirm {
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")] 
    param()
    
    $ConfirmImpact = $MyInvocation.MyCommand.ScriptBlock.Attributes[0].ConfirmImpact
    
    $Confirm = [int]$ConfirmPreference -le [int]$ConfirmImpact
    
    return $Confirm;
}

We can easily test if it successfully returns a valid `Confirm` value by calling it from another function:


Function Outer { 
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")] 
    param() 
    
    Test-Confirm 
}

As expected, calling `Outer` with the `-Confirm` flag will return `True` and without it, `False`.

No comments: