Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use -confirm in PowerShell

Tags:

powershell

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 following code but its not working:

write-host "Are you Sure You Want To Proceed:"  -Confirm 
like image 808
user3770612 Avatar asked Jul 09 '14 08:07

user3770612


People also ask

What is $_ in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

What is $using in PowerShell?

Beginning in PowerShell 3.0, you can use the Using scope modifier to identify a local variable in a remote command. The syntax of Using is as follows: $Using:<VariableName> In the following example, the $ps variable is created in the local session, but is used in the session in which the command runs.


2 Answers

-Confirm is a switch in most PowerShell cmdlets that forces the cmdlet to ask for user confirmation. What you're actually looking for is the Read-Host cmdlet:

$confirmation = Read-Host "Are you Sure You Want To Proceed:" if ($confirmation -eq 'y') {     # proceed } 

or the PromptForChoice() method of the host user interface:

$title    = 'something' $question = 'Are you sure you want to proceed?'  $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription] $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes')) $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))  $decision = $Host.UI.PromptForChoice($title, $question, $choices, 1) if ($decision -eq 0) {     Write-Host 'confirmed' } else {     Write-Host 'cancelled' } 

Edit:

As M-pixel pointed out in the comments the code could be simplified further, because the choices can be passed as a simple string array.

$title    = 'something' $question = 'Are you sure you want to proceed?' $choices  = '&Yes', '&No'  $decision = $Host.UI.PromptForChoice($title, $question, $choices, 1) if ($decision -eq 0) {     Write-Host 'confirmed' } else {     Write-Host 'cancelled' } 
like image 149
Ansgar Wiechers Avatar answered Sep 21 '22 04:09

Ansgar Wiechers


This is a simple loop that keeps prompting unless the user selects 'y' or 'n'

$confirmation = Read-Host "Ready? [y/n]" while($confirmation -ne "y") {     if ($confirmation -eq 'n') {exit}     $confirmation = Read-Host "Ready? [y/n]" } 
like image 34
dallyack Avatar answered Sep 21 '22 04:09

dallyack