How to Use -confirm in PowerShell

后端 未结 10 1437
遥遥无期
遥遥无期 2020-12-07 20:10

I\'m trying to take user input and before proceeding I would like get a message on screen and than a confirmation, whether user wants to proceed or not. I\'m using the follo

10条回答
  •  天涯浪人
    2020-12-07 20:50

    Here is the documentation from Microsoft on how to request confirmations in a cmdlet. The examples are in C#, but you can do everything shown in PowerShell as well.

    First add the CmdletBinding attribute to your function and set SupportsShouldProcess to true. Then you can reference the ShouldProcess and ShouldContinue methods of the $PSCmdlet variable.

    Here is an example:

    function Start-Work {
        <#
        .SYNOPSIS Does some work
        .PARAMETER Force
            Perform the operation without prompting for confirmation
        #>
        [CmdletBinding(SupportsShouldProcess=$true)]
        param(
            # This switch allows the user to override the prompt for confirmation
            [switch]$Force
        )
        begin { }
        process {
            if ($PSCmdlet.ShouldProcess('Target')) {
                if (-not ($Force -or $PSCmdlet.ShouldContinue('Do you want to continue?', 'Caption'))) {
                    return # user replied no
                }
    
                # Do work
            }
    
        }
        end { }
    }
    

提交回复
热议问题