Freigeben über


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 image

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 image

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"

Comments

  • Anonymous
    November 27, 2017
    LoadWithPartialName is long deprecated. The current method would be:Add-Type -AssemblyName 'System.Windows.Forms'Most of those double quoted values should be single quoted for better performance.Function name should follow verb-noun format.Try this:function Invoke-GuiPause { [CmdletBinding()] param ([string] $Message = 'Click OK to continue or CANCEL to exit script', [string] $Title = 'Continue or Cancel') Add-Type -AssemblyName 'System.Windows.Forms' $MsgBox = [Windows.Forms.MessageBox] $Decision = $MsgBox::Show($Message, $Title, 'OkCancel', 'Information') If ($Decision -eq 'Cancel') {exit}}
    • Anonymous
      December 17, 2017
      Good one Pat, thanks ! Don't know when "LoadWithPartialName" will cease to work though, as it's still been retained for backward compatibility. I corrected it in the post - thanks Pat !