How to Use -confirm in PowerShell

后端 未结 10 1436
遥遥无期
遥遥无期 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:40

    A slightly prettier function based on Ansgar Wiechers's answer. Whether it's actually more useful is a matter of debate.

    function Read-Choice(
       [Parameter(Mandatory)][string]$Message,
       [Parameter(Mandatory)][string[]]$Choices,
       [Parameter(Mandatory)][string]$DefaultChoice,
       [Parameter()][string]$Question='Are you sure you want to proceed?'
    ) {
        $defaultIndex = $Choices.IndexOf($DefaultChoice)
        if ($defaultIndex -lt 0) {
            throw "$DefaultChoice not found in choices"
        }
    
        $choiceObj = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
    
        foreach($c in $Choices) {
            $choiceObj.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList $c))
        }
    
        $decision = $Host.UI.PromptForChoice($Message, $Question, $choiceObj, $defaultIndex)
        return $Choices[$decision]
    }
    

    Example usage:

    PS> $r = Read-Choice 'DANGER!!!!!!' '&apple','&blah','&car' '&blah'
    
    DANGER!!!!!!
    Are you sure you want to proceed?
    [A] apple  [B] blah  [C] car  [?] Help (default is "B"): c
    PS> switch($r) { '&car' { Write-host 'caaaaars!!!!' } '&blah' { Write-Host "It's a blah day" } '&apple' { Write-Host "I'd like to eat some apples!" } }
    caaaaars!!!!
    

提交回复
热议问题