PowerTip: Wire Up PowerShell GUI Buttons


Summary: Learn to use the OK and Cancel buttons in a Windows PowerShell GUI.

Hey, Scripting Guy! Question How can I use Windows PowerShell to get my GUI’s OK and Cancel buttons to trigger when
           the user presses ENTER or Escape?

Hey, Scripting Guy! Answer Assign the OK and Cancel button objects to your form’s AcceptButton and CancelButton properties:

$form.AcceptButton = $OKButton
$form.CancelButton = $CancelButton

Comments (5)

  1. Hello
    Please check my article at codeproject for extensive coverage of using Windows Forms and WPF with Powershell for
    typical Powershell tasks which often require various option prompts.

    http://www.codeproject.com/Articles/799161/Dealing-with-Powershell-Inputs-via-Basic-Windows-F#9FF54089465749EEB174C10748114593

    Many common Windows form patterns are covered there to create user-friendly
    The daily devops tasks of running Powershell in a complex environment become a less challenging task

    Code for all samples is provided.

    Thanks,

    Serguei Kouzmine

  2. David Wyatt says:

    Yep! Assigning values to the DialogResult properties is mentioned in the main article (

    http://blogs.technet.com/b/heyscriptingguy/archive/2014/08/02/weekend-scripter-fixing-powershell-gui-examples.aspx ), but not in the PowerTip.

  3. jrv says:

    Also:

    $button1.DialogResult = ‘Cancel’
    $buttonOK.DialogResult = ‘OK’

    The "DialogResult" can take these values and all will terminate the form and return the enum value.

    [Enum]::GetNames([System.Windows.Forms.DialogResult])

    http://msdn.microsoft.com/en-us/library/system.windows.forms.dialogresult(v=vs.110).aspx