Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ask for confirmation? [duplicate]

Tags:

powershell

I want to create a confirmation box. I want to have a popup box that says that it appears that this is the factory key. Do you wish to continue? and if so proceed with the rest of the script if not, exit script.

The following is my script:

if (Test-Path $USB2\sources\install3.swm) { 
    $caption = "*** IT APPEARS THIS IS A FACTORY KEY ***"    
    $message = "Are you Sure You Want To Proceed:"
    [int]$defaultChoice = 1
    $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "I understand, flash over it."
    $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No"
    $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 {
        Stop-Process -Id $PID
    }
}

See the bit, $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no). Where I am stuck is the "Your Choice was yes" I don't need that... I just need it to continue with the script if yes. How do I do that?

like image 940
Rj McKay Avatar asked Nov 01 '25 14:11

Rj McKay


1 Answers

Consider using the System.Windows.MessageBox...

Add-Type -AssemblyName PresentationFramework
[System.Windows.MessageBox]::Show('It appears that this is the factory key. Do you wish to continue?', 'Confirmation', 'YesNo');

enter image description here

For your use case,

# You need this to use System.Windows.MessageBox
Add-Type -AssemblyName 'PresentationFramework'

# By default, you're blasting the USB drive
$continue = 'Yes'

# If you see the file, prompt the user
if ( $(Test-Path -Path "${USB2}\sources\install3.swm") ) { 
    $caption = "*** IT APPEARS THIS IS A FACTORY KEY ***"    
    $message = "Are you Sure You Want To Proceed:"

    $continue = [System.Windows.MessageBox]::Show($message, $caption, 'YesNo');
}

if ($continue -eq 'Yes') {
    # The user either (a) said "yes" to the "do you prompt" or
    # (b) the file didn't exist.

    Write-Output "Flash over..."
    # ...do the flashing here...
} else {
    # The user said "no" to the flash prompt

    Write-Output "Terminating process..."
    Start-Sleep 1
}

The message box will return Yes or No, and you can use that in your control flow to determine next steps. If that includes closing the window, call exit.

like image 144
Adam Avatar answered Nov 04 '25 11:11

Adam