Есть ли способ отобразить всплывающее окно с сообщениями в PowerShell, которое совместимо как с системами Windows, так и с MacOS? - PullRequest
1 голос
/ 05 ноября 2019

Я знаю, что вы можете сделать что-то подобное в PowerShell Version 5 (показано ниже), но есть ли способ воспроизвести всплывающее окно сообщения, которое работает на платформах Windows и Mac OS?

$ButtonType = [System.Windows.Forms.MessageBoxButtons]::OK

$MessageIcon = [System.Windows.Forms.MessageBoxIcon]::Information

$MessageBody = "Message Body goes here"

$MessageTitle = "Title"

$Result = [System.Windows.Forms.MessageBox]::Show($MessageBody,$MessageTitle,$ButtonType,$MessageIcon)

ВыводКодекса выше

enter image description here

1 Ответ

0 голосов
/ 06 ноября 2019

Функция Show-MessageBox, определенная ниже , предлагает функциональность окна сообщений в Windows и macOS , смоделированную в классе WinForms MessageBox.

Примеры:

# Message box with custom message, OK button only, and default title and icon
$null = Show-MessageBox 'some message'

# Message box with custom message and title, buttons OK and cancel, and 
# the Stop icon (critical error)
# Return value is the name of the button chosen.
$buttonChosen = Show-MessageBox 'some message' 'a title' -Buttons OKCancel -Icon Stop

Синтаксис (разбит на несколько строк для удобства чтения):

Show-MessageBox [-Message] <string> [[-Title] <string>] 
                [[-Buttons] {OK | OKCancel | AbortRetryIgnore | YesNoCancel | YesNo | RetryCancel}] 
                [-Icon {Information | Warning | Stop}] 
                [-DefaultButtonIndex {0 | 1 | 2}]

Примечание:

  • В macOS, AppleScript's display alertКоманда используется для создания окна сообщения.

    • В то время как эта команда номинально различает уровни серьезности informational, warning и critical, первые два показывают то же самое значок - папка - и последний перекрывает значок папки только с восклицательным знаком .
  • Для кросс-платформенной согласованности выходное значение равно строка , а именно название кнопки, нажатой пользователем.

  • -DefaultButtonIndex - это индекс на основе 0 кнопки, которая будет нажата, когдапользователь просто нажимает Введите .

    • Windows: если присутствует кнопка Cancel, Esc нажимает ее.
    • macOs: если No, Abort или Cancel кнопка присутствует и не является кнопкой по умолчанию, Esc нажимает ее.

Show-MessageBox исходный код :

function Show-MessageBox {
  [CmdletBinding(PositionalBinding=$false)]
  param(
    [Parameter(Mandatory, Position=0)]
    [string] $Message,
    [Parameter(Position=1)]
    [string] $Title,
    [Parameter(Position=2)]
    [ValidateSet('OK', 'OKCancel', 'AbortRetryIgnore', 'YesNoCancel', 'YesNo', 'RetryCancel')]
    [string] $Buttons = 'OK',
    [ValidateSet('Information', 'Warning', 'Stop')]
    [string] $Icon = 'Information',
    [ValidateSet(0, 1, 2)]
    [int] $DefaultButtonIndex
  )

  # So that the $IsLinux and $IsMacOS PS Core-only
  # variables can safely be accessed in WinPS.
  Set-StrictMode -Off

  $buttonMap = @{ 
    'OK'               = @{ buttonList = 'OK'; defaultButtonIndex = 0 }
    'OKCancel'         = @{ buttonList = 'OK', 'Cancel'; defaultButtonIndex = 0; cancelButtonIndex = 1 }
    'AbortRetryIgnore' = @{ buttonList = 'Abort', 'Retry', 'Ignore'; defaultButtonIndex = 2; ; cancelButtonIndex = 0 }; 
    'YesNoCancel'      = @{ buttonList = 'Yes', 'No', 'Cancel'; defaultButtonIndex = 2; cancelButtonIndex = 2 };
    'YesNo'            = @{ buttonList = 'Yes', 'No'; defaultButtonIndex = 0; cancelButtonIndex = 1 }
    'RetryCancel'      = @{ buttonList = 'Retry', 'Cancel'; defaultButtonIndex = 0; cancelButtonIndex = 1 }
  }

  $numButtons = $buttonMap[$Buttons].buttonList.Count
  $defaultIndex = [math]::Min($numButtons - 1, ($buttonMap[$Buttons].defaultButtonIndex, $DefaultButtonIndex)[$PSBoundParameters.ContainsKey('DefaultButtonIndex')])
  $cancelIndex = $buttonMap[$Buttons].cancelButtonIndex

  if ($IsLinux) { 
    Throw "Not supported on Linux." 
  }
  elseif ($IsMacOS) {

    $iconClause = if ($Icon -ne 'Information') { 'as ' + $Icon -replace 'Stop', 'critical' }
    $buttonClause = "buttons { $($buttonMap[$Buttons].buttonList -replace '^', '"' -replace '$', '"' -join ',') }"

    $defaultButtonClause = 'default button ' + (1 + $defaultIndex)
    if ($null -ne $cancelIndex -and $cancelIndex -ne $defaultIndex) {
      $cancelButtonClause = 'cancel button ' + (1 + $cancelIndex)
    }

    $appleScript = "display alert `"$Title`" message `"$Message`" $iconClause $buttonClause $defaultButtonClause $cancelButtonClause"            #"

    Write-Verbose "AppleScript command: $appleScript"

    # Show the dialog.
    # Note that if a cancel button is assigned, pressing Esc results in an
    # error message indicating that the user canceled.
    $result = $appleScript | osascript 2>$null

    # Output the name of the button chosen (string):
    # The name of the cancel button, if the dialog was canceled with ESC, or the
    # name of the clicked button, which is reported as "button:<name>"
    if (-not $result) { $buttonMap[$Buttons].buttonList[$buttonMap[$Buttons].cancelButtonIndex] } else { $result -replace '.+:' }
  }
  else { # Windows
    Add-Type -Assembly System.Windows.Forms        
    # Show the dialog.
    # Output the chosen button as a stringified [System.Windows.Forms.DialogResult] enum value,
    # for consistency with the macOS behavior.
    [System.Windows.Forms.MessageBox]::Show($Message, $Title, $Buttons, $Icon, $defaultIndex * 256).ToString()
  }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...