MessageBox - PowerShell


Overview

The MessageBox command displays a standard Windows message box, providing a simple way to interact with users through the PowerShell console. It’s useful for displaying messages, getting user input, or prompting for user confirmation.

Syntax

MessageBox [-Message] <string> [-Caption] <string> [-Type] <MessageType> [-Buttons] <PushButtonType> [-DefaultButton] <PushButtonType> [-Icon] <IconType> [-Timeout] <int> [-Response] <string>

Options/Flags

| Option | Description | Default Value |
| ——————– | ———————————————————————————————————————————————————————– | ————– |
| -Message | The message to display in the message box. | N/A |
| -Caption | The title of the message box. | “PowerShell” |
| -Type | The type of message box to display. Valid values include: Error, Information, Question, Warning, and Default. | “Default” |
| -Buttons | The buttons to display in the message box. Valid values include: OK, OKCancel, YesNo, YesNoCancel, AbortRetryIgnore, and Custom. | “OK” |
| -DefaultButton | The button that is selected as the default when the message box is displayed. | N/A |
| -Icon | The icon to display in the message box. Valid values include: Error, Information, Question, Warning, and None. | “None” |
| -Timeout | The number of milliseconds to display the message box before automatically closing it. | N/A |
| -Response | A variable to store the user’s response to the message box. | N/A |

Examples

Display a simple message box:

MessageBox -Message "Hello, world!"

Display a message box with custom buttons:

$buttons = [System.Windows.Forms.MessageBoxButtons]::YesNoCancel
MessageBox -Message "Proceed with the operation?" -Buttons $buttons

Display a message box with a timeout:

MessageBox -Message "This message will close in 5 seconds." -Timeout 5000

Get the user’s response from a message box:

$response = MessageBox -Message "Are you sure you want to delete the file?" -Buttons "YesNo" -Response $true
if ($response) {
    # User clicked Yes
}

Common Issues

  • Empty or invalid response: The -Response variable may not be set if the message box is closed without selecting a button.
  • Unexpected behavior: Ensure that the values provided for options are correct and correspond to valid types.

Integration

The MessageBox command can be used in combination with other PowerShell commands to create complex scripts and workflows. For example, you could use it as a part of a confirmation process before executing a destructive operation.

  • Write-Host
  • Show-Message
  • Read-Host