M. Simon
M. Simon

Reputation: 111

How do I stop my script when I click cancel on a popup box?

I need to be able to stop my script when the user clicks cancel on a certain popup box. Part of the script goes as follows:

$OS = (Get-WmiObject -class Win32_OperatingSystem).caption

if ($OS -ne "Microsoft Windows 10 *"){

   $wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("This computer is currently running $OS. To continue with the 
script click OK, otherwise click Cancel.",0,"Windows 10 
Notification",0x1)

}

That is where the user has to decide to terminate the script progress or continue. And I need to be able to continue the script when the user clicks OK, but stop the script from continuing when he clicks Cancel.

Upvotes: 0

Views: 2146

Answers (2)

Guenther Schmitz
Guenther Schmitz

Reputation: 1999

I prefer using Windows Forms and updated the script accordingly. You can find more examples here.

I also changed the if condition because you where checking if the variable $OS was exactly "Microsoft Windows 10 *"; to check if it begins with the string use -notlike instead of -ne.

$OS = (Get-WmiObject -class Win32_OperatingSystem).caption

if ($OS -notlike "Microsoft Windows 10 *") {
    $PopupTitle = "Windows 10 Notification"
    $PopupMessage = "This computer is currently running $OS. To continue with the script click OK, otherwise click Cancel."
    $PopupOptions = "OkCancel"
    $PopupAnswer = [System.Windows.Forms.MessageBox]::Show($PopupMessage,$PopupTitle,$PopupOptions,[System.Windows.Forms.MessageBoxIcon]::Exclamation)

    if ($PopupAnswer -eq "Cancel") {
        Break
    }
}

Upvotes: 0

ShanayL
ShanayL

Reputation: 1247

you can capture the popup answer in a variable and use an if-statement to stop the script with Break. Try using this:

$OS = (Get-WmiObject -class Win32_OperatingSystem).caption

if ($OS -ne "Microsoft Windows 10 *"){

    $wshell = New-Object -ComObject Wscript.Shell
    $answer = $wshell.Popup("This computer is currently running $OS. To continue with the 
    script click OK, otherwise click Cancel.",0,"Windows 10 
    Notification",0x1)

    if($answer -eq 2){Break}

}

$answer shows as 1 for OK and 2 for Cancel

Upvotes: 1

Related Questions