How-to: Display user messages in a popup messagebox.

A function to display messages in a popup message box, with options for OK/Cancel, Yes/No or Retry/Cancel buttons.

function msgbox {
param (
    [string]$Message,
    [string]$Title = 'Message box title',   
    [string]$buttons = 'OKCancel'
)
# This function displays a message box by calling the .Net Windows.Forms (MessageBox class)
 
# Load the assembly
Add-Type -AssemblyName System.Windows.Forms | Out-Null
 
# Define the button types
switch ($buttons) {
   'ok' {$btn = [System.Windows.Forms.MessageBoxButtons]::OK; break}
   'okcancel' {$btn = [System.Windows.Forms.MessageBoxButtons]::OKCancel; break}
   'YesNoCancel' {$btn = [System.Windows.Forms.MessageBoxButtons]::YesNoCancel; break}
   'YesNo' {$btn = [System.Windows.Forms.MessageBoxButtons]::yesno; break}
   'RetryCancel'{$btn = [System.Windows.Forms.MessageBoxButtons]::RetryCancel; break}
   default {$btn = [System.Windows.Forms.MessageBoxButtons]::RetryCancel; break}
}
 
# Display the message box
$Return=[System.Windows.Forms.MessageBox]::Show($Message,$Title,$btn)

# Display the option chosen by the user:
$Return
}

The MessageBox Button options are from the standard .Net framework MessageBox class.

Examples

Calling the MessageBox function defined above:

PS C:> msgbox "test message"

PS C:> $result = msgbox -message "test message" -title "Hello" -buttons YesNoCancel
or
PS C:> $result = msgbox "test message" "Hello" yesnocancel

“My message to everyone: the next time you hear about migrant children near the border, just picture them as your own. Then think what you would want our government to do” ~ Al Sharpton

Related PowerShell Cmdlets

Functions and Filters - Write a named block of code.


 
Copyright © 1999-2024 SS64.com
Some rights reserved