Proper use of ConfirmImpact and a Force parameter

Welcome Forums General PowerShell Q&A Proper use of ConfirmImpact and a Force parameter

This topic contains 1 reply, has 2 voices, and was last updated by

1 year, 1 month ago.

  • Author
  • #91556

    Points: 67
    Rank: Member

    Consider the test script shown below:

    function New-Folder {
                       ConfirmImpact = 'High')]
            [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.

  • #91559

    Points: 790
    Helping Hand
    Rank: Major Contributor

    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

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

    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.

The topic ‘Proper use of ConfirmImpact and a Force parameter’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort