I am attempting to write a script that will display a message box with yes/no buttons. I am wanting “Yes” to close an open application & “No” to end the script.
I have written a few mutations of the code below but the best I could get was both yes & no closed the application. Here’s my code:
Add-Type -AssemblyName PresentationCore,PresentationFramework
[System.Windows.MessageBox]::Show('Do you want to close TAS?',‘WARNING’,‘YesNo’)
[System.Windows.MessageBoxImage]::Warning
$msgBoxInput = [System.Windows.MessageBoxButton]::Show(‘YesNo’)
switch ($msgBoxInput) {
‘Yes’ {
Stop-Process -Name ATIS-Broadcaster2
‘YES’
}
‘No’ {
Exit-PSSession
‘NO’
}
}
Try the following:
Add-Type -AssemblyName PresentationCore, PresentationFramework
switch (
[System.Windows.MessageBox]::Show(
'Do you want to close TAS?',
'WARNING',
'YesNo',
'Warning'
)
) {
'Yes' {
'YES'
# Stop-Process -Name ATIS-Broadcaster2
}
'No' {
'NO'
# Exit-PSSession
}
}
Note: I've also converted your "curly" single quotes to regular, ASCII-range ones; while PowerShell accepts both types, it's better to stick with the latter.
See the System.Windows.MessageBox
docs.
Note that the parameters to which 'YesNo'
and 'Warning'
are passed, as well as the .Show()
method's return value, expect / return enumeration values[1].
However, PowerShell's automatic type conversions conveniently allow just specifying the value names as strings, such as 'YesNo'
, 'Warning'
or 'Yes'
in lieu of [System.Windows.MessageBoxButton]::YesNo
, [System.Windows.MessageBoxImage]::Warning
, and [System.Windows.MessageBoxResult]::Yes
, which simplifies the code.
[1] That is, instances of value types derived from System.Enum
, which define discrete numeric values under symbolic names.