This will seem dumb, but do you need a message box in your script? Normally no, but when you are using a script for an end-user, you might need it. So, let us take a look at how to do it real quick.
The Script
function Invoke-SHDMessageBox {
[cmdletbinding()]
param (
[Parameter(HelpMessage = "Message Title", Mandatory = $true)][Alias('Title', 'header')][string]$MessageTitle,
[Parameter(HelpMessage = "Message Body", Mandatory = $true)][Alias('Boby', 'Information')][string]$MessageBody,
[Parameter(HelpMessage = "Message Buttons", Mandatory = $true)][Alias('Buttons')][validateset("YesNo", "YesNoCancel", "OK", "OKCancel")][string]$MessageButtons,
[Parameter(HelpMessage = "Message Image", Mandatory = $true)][Alias('Image')][validateset("Asterisk", "Error", "Exclamation", "Hand", "Information", "None", "Question", "Stop", "Warning")][string]$Messagetype
)
Add-Type -AssemblyName PresentationCore, PresentationFramework
$ButtonType = [System.Windows.MessageBoxButton]::$MessageButtons
$MessageIcon = [System.Windows.MessageBoxImage]::$Messagetype
$Results = [System.Windows.MessageBox]::Show($Messageboxbody, $MessageboxTitle, $ButtonType, $messageicon)
Return $Results
}
The Breakdown
Lets break this guy down. First thing first, the parameters.
- MessageTitle – What will be presented as the title of the message box.
- MessageBody – The message itself.
- MessageButtons – What types of buttons.
- YesNo
- YesNoCancel
- OK
- OKCancel
- MessageType – The type of image will be presented.
All the parameters are mandatory. None can be passed by the pipeline. All are single strings instead of my normal list of strings. It’s far easier that way.
Next, we need to add the assembly for the box. These are PresentationCore and PresentationFramework.
Add-Type -AssemblyName PresentationCore, PresentationFramework
Next, we just add items to the variables we will be using. The input from the parameters and their validate set. For the buttons themselves we call upon the power of the assembly we added earlier. [System.Windows.*] In the button case, the * becomes MessageBoxButton.
$ButtonType = [System.Windows.MessageBoxButton]::$MessageButtons
Then the message box image will be the same way, but with messageboximage.
$MessageIcon = [System.Windows.MessageBoxImage]::$Messagetype
Then we put it all together with the messagebox itself.
$Results = [System.Windows.MessageBox]::Show($MessageBody, $MessageTitle, $ButtonType, $messageicon)
The first part of the show is the body followed by the title, then followed by the buttons, and finally the image. Notice I pipe it into Results. I do this because we want to return those results.
Return $Results
That’s it! Once you return the results, you can test them with an if statement. Come back Monday for a ballon notification function.