How to Use -confirm in PowerShell

后端 未结 10 1431
遥遥无期
遥遥无期 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 21:03

    Read-Host is one example of a cmdlet that -Confirm does not have an effect on.-Confirm is one of PowerShell's Common Parameters specifically a Risk-Mitigation Parameter which is used when a cmdlet is about to make a change to the system that is outside of the Windows PowerShell environment. Many but not all cmdlets support the -Confirm risk mitigation parameter.

    As an alternative the following would be an example of using the Read-Host cmdlet and a regular expression test to get confirmation from a user:

    $reply = Read-Host -Prompt "Continue?[y/n]"
    if ( $reply -match "[yY]" ) { 
        # Highway to the danger zone 
    }
    

    The Remove-Variable cmdlet is one example that illustrates the usage of the -confirm switch.

    Remove-Variable 'reply' -Confirm
    

    Additional References: CommonParameters, Write-Host, Read-Host, Comparison Operators, Regular Expressions, Remove-Variable

提交回复
热议问题