How to Use -confirm in PowerShell

Powershell

Powershell Problem Overview


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

Powershell Solutions


Solution 1 - Powershell

-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'
}

Solution 2 - Powershell

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]"
}

Solution 3 - Powershell

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

Solution 4 - Powershell

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 { }
}

Solution 5 - Powershell

write-host does not have a -confirm parameter.

You can do it something like this instead:

    $caption = "Please Confirm"    
    $message = "Are you Sure You Want To Proceed:"
    [int]$defaultChoice = 0
    $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Do the job."
    $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Do not do the job."
    $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
    $choiceRTN = $host.ui.PromptForChoice($caption,$message, $options,$defaultChoice)
 
if ( $choiceRTN -ne 1 )
{
   "Your Choice was Yes"
}
else
{
   "Your Choice was NO"
}

Solution 6 - Powershell

For when you want a 1-liner

while( -not ( ($choice= (Read-Host "May I continue?")) -match "y|n")){ "Y or N ?"}

Solution 7 - Powershell

Write-Warning "This is only a test warning." -WarningAction Inquire

from: https://serverfault.com/a/1015583/584478

Solution 8 - Powershell

Here's a solution I've used, similiar to Ansgar Wiechers' solution;

$title = "Lorem"
$message = "Ipsum"

$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "This means Yes"
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "This means No"

$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

$result = $host.ui.PromptForChoice($title, $message, $Options, 0)

Switch ($result)
     {
          0 { "You just said Yes" }
          1 { "You just said No" }
     }

Solution 9 - Powershell

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!!!!

Solution 10 - Powershell

This version asks if the user wants to perform an action before continuing with the rest of the script.

DO
{
$confirmation = Read-Host "Do want Action before continue? [Y/N]"
if ($confirmation -eq 'y') {
   write-Host "Doing the Action"
   }
} While (($confirmation -ne 'y') -and ($confirmation -ne 'n'))

Solution 11 - Powershell

I prefer a popup.

$shell = new-object -comobject "WScript.Shell"
$choice = $shell.popup("Insert question here",0,"Popup window title",4+32)

If $choice equals 6, the answer was Yes If $choice equals 7, the answer was No

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3770612View Question on Stackoverflow
Solution 1 - PowershellAnsgar WiechersView Answer on Stackoverflow
Solution 2 - PowershelldallyackView Answer on Stackoverflow
Solution 3 - PowershellChris SmithView Answer on Stackoverflow
Solution 4 - PowershellZack BolinView Answer on Stackoverflow
Solution 5 - PowershellCB.View Answer on Stackoverflow
Solution 6 - PowershellChris F CarrollView Answer on Stackoverflow
Solution 7 - PowershellKLCView Answer on Stackoverflow
Solution 8 - PowershellsamprogView Answer on Stackoverflow
Solution 9 - Powershelljpmc26View Answer on Stackoverflow
Solution 10 - PowershellOrigamiEyeView Answer on Stackoverflow
Solution 11 - PowershellDacian BrinzasView Answer on Stackoverflow