PowerShell post - GUI Pause to give user choice to continue or abort a PowerShell script execution
Hi all, this post is to show you how to use a GUI pause, basically a message box which when you call it, it’s asking you to continue (click “Ok”) or abort (click “Cancel”) a script or a set of PowerShell instructions
Just put the below function in the beginning of your script, or in the “Functions” definitions area of your script, and just call the function name (GUIPAUSE in the below example) whenever you wish to continue or abort the running script / set of instructions :
#region BEGIN PAUSE FUNCTION DEFINITION
Function GUIPAUSE ($Message = "Click OK to continue or CANCEL to exit script", $Title = "Continue or Cancel") {
Add-Type -AssemblyName System.Windows.Forms | Out-Null
$MsgBox = [System.Windows.Forms.MessageBox]
$Decision = $MsgBox::Show($Message,$Title,"OkCancel", "Information")
If ($Decision -eq "Cancel") {exit}
}
#endregion
To customize the Pause message you can use the following synthax when calling the “GUIPAUSE” function :
GUIPAUSE -Message "MyMessage" -Title "MyTitle"
Examples:
GUIPAUSE
=> launches the Pause window with “OK” and “Cancel” to continue or abort the script
GUIPAUSE -Message "I Love PowerShell ... click OK to continue or Cancel to abort script" -Title "Another Title"
=> same as above with custom message and box title
In the below example, after printing each line, you’ll get a Pop-Up to ask you to continue or to abort/cancel the script execution (you must have registered the GUIPAUSE function before)…
# SAMPLE CODE TO ILLUSTRATE GUIPAUSE #
Write-host "Coucou ! Script launched"
GUIPAUSE
Write-Host "Continuing ... instruction 001"
GUIPAUSE
Write-Host "Continuing again ... instruction 002"
GUIPAUSE
Write-Host "Ending ... Instruction 003"