Author Posts

January 16, 2018 at 4:13 am

Consider the test script shown below:

function New-Folder {
    [cmdletbinding(SupportsShouldProcess,
                   ConfirmImpact = 'High')]
    param(
        [parameter(ValueFromPipeline)]
        [string[]] $Item,

        [switch] $Force
    )

    process {
        foreach ($i in $Item) {
            if ($PSCmdlet.ShouldProcess($i)) {  
                Write-Verbose "Creating $i"      
                New-Item -Name $i -ItemType Directory -Confirm:$false -Force:$Force | Out-Null
            }
        }
    }
}

When the ConfirmImpact is set to 'High' I can't figure out a way to properly implement the Force parameter to bypass all confirm prompts when the Force switch is used. I've read it's bad practice to implement $Force as part of the ShouldProcess conditional statement so where should I implement $Force?

Any help is appreciated.

January 16, 2018 at 4:54 am

Well, it and things associated with ShoudProcess is a matter of what you are trying o do at the time.
Function nesting has impact, chosen cmdlet has an impact, etc., at their time of use. Full disclousure, this is not something I really use, as to date I've had little reason to. However, one of the better write-ups I've seen on the whole ShouldProcess thing is here:

PowerShell SupportsShouldProcess Worst & Best Practices

http://iheartpowershell.blogspot.co.za/2013/05/powershell-supportsshouldprocess-worst.html

Maybe you can glean a clear thought process after reading it. This is of course assuming you have already read the following.

https://msdn.microsoft.com/en-us/library/bb204629(v=vs.85).aspx
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_cmdletbindingattribute?view=powershell-5.1

Based on the notes I keep on this an other topics –

It has been positioned that [CmdletBinding(ConfirmImpact="High") only tells your script the behaviour to use when you use the ShouldProcess method. It does NOT set the ConfirmPreference.

The call to the ShouldProcess method displays a confirmation prompt only when the ConfirmImpact argument is equal to or greater than the value of the $ConfirmPreference preference variable where as ConfirmImpact is an enum, where High=3, Medium=2, Low=1, None=0

New-Item on an item that doesn't exist has a Confirm of Med(2), 2 < High(3), so no prompt. When you set it to Medium again, 2 -eq 2, it prompts. Remove-Item has a default impact of High(3) since it results in data loss, 3 -ge (any confirm preference), so it always prompts.