【问题标题】:How to return specifi error level by clicking a button in a form of GUI in Powershell?如何通过单击 Powershell 中 GUI 形式的按钮返回特定的错误级别?
【发布时间】:2019-04-16 06:38:19
【问题描述】:

我将使用 GUI 并单击按钮以返回具有特定数字的错误级别。它仅返回 $Auto_Button 的错误级别值,并且当脚本执行时 GUI 消失。

Add-Type -AssemblyName System.Windows.Forms $Font = New-Object System.Drawing.Font("Times New Roman",13)

$MainForm = New-Object System.Windows.Forms.Form
$MainForm.Text = "Process"
$MainForm.Width = 500
$MainForm.Height = 200
$MainForm.StartPosition = "CenterScreen"
$MainForm.BackColor = "#e2e2e2"

$Title = New-Object System.Windows.Forms.Label
$Title.Font = $Font
$Title.Text = "Which process do you want to choose?"
$Title.Location = New-Object System.Drawing.Size(100,30)
$Title.Size = New-Object System.Drawing.Size(500,30)
$MainForm.Controls.Add($Title)

$Auto_Button = {$MainForm.Close()}
               Exit 10   

$Manual_Button = $MainForm.Close()}
               Exit 30

$Automatic = New-Object System.Windows.Forms.Button
$Automatic.Location = New-Object System.Drawing.Size(110,80)
$Automatic.Size = New-Object System.Drawing.Size(100,30)
$Automatic.Text = "Automatically"
$Automatic.Font = 'Microsoft Sans Serif,10'
$Automatic.BackColor = "#e47104"
$Automatic.Add_Click($Auto_Button)
$MainForm.Controls.Add($Automatic)

$Manual = New-Object System.Windows.Forms.Button
$Manual.Location = New-Object System.Drawing.Size(270,80)
$Manual.Size = New-Object System.Drawing.Size(100,30)
$Manual.Text = "Manually"
$Manual.Font = 'Microsoft Sans Serif,10'
$Manual.BackColor = "#e47104"
$Manual.Add_Click($Manual_Button)
$MainForm.Controls.Add($Manual)

$MainForm.ShowDialog()

【问题讨论】:

  • 通常此类错误消息具有Details 按钮,可显示有关异常的所有信息。在那里你会看到System.Management.Automation.ExitException,这意味着当你调用exit时发生了一些事情。
  • 我更新问题
  • 为什么你删除了代码?作为一个通用的答案:在按钮的处理函数中将一些全局变量设置为一个特定的值,然后返回这个变量。
  • 我更新了问题
  • @montonero ExitExceptionexit 所做的。这就是 PowerShell 退出多个嵌套代码级别的方式,其中一些代码可能不是 PowerShell 起源的。但是 Windows 窗体决定处理所有事情并显示精美的对话框,而不是将异常传递给调用者。

标签: powershell user-interface errorlevel


【解决方案1】:

使用全局变量来存储结果。

$Auto_Button = ({ $global:result=10
                  $MainForm.Close() })

$Manual_Button = ({ $global:result=20
                    $MainForm.Close() })

...

$result=0
$MainForm.ShowDialog()

$result | Out-File .\exit.txt
exit $result

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2015-12-11
    相关资源
    最近更新 更多