首页 > 解决方案 > Try.. catch.. 最终在 Read-Host 期间失败

问题描述

当脚本执行Read-Hostcmdlet 时,关闭窗口不会激活finally块。下面是一个任意但功能最少的示例。我正在使用 PowerShell 5.0。Beep() 只是为了让 finally 块的执行显而易见。

try {
    $value= Read-Host -Prompt "Input"
    sleep 5
} finally {
    [Console]::Beep(880,1000)
}
  1. 如果您在Read-Hostfinally块不会执行期间通过单击红色 X 来关闭窗口。
  2. 如果在sleepfinally将执行期间通过单击红色 X 关闭窗口。
  3. 如果您在任何时候使用 Ctrl-C 中断,该finally块将执行。

finally关于为什么在 a 期间关闭窗口时块没有执行,我是否缺少一些基本的东西Read-Host

完整案例涉及在 Amazon Snowball 设备上启动服务,如果脚本关闭则需要停止服务。完整的案例行为反映了上面的示例案例。

编辑:由于评论说 $input 是保留变量,将变量从 $input 更改为 $value。不改变行为。

标签: powershelltry-catch-finallyread-host

解决方案


继续我的评论。

控制台主机有点不灵活,具体取决于您在本机上所做的事情。该“X”与 PowerShell 会话/进程有关,而不是与其中运行的代码有关。因此,为什么 CRTL+C 有效,因为您要停止代码运行,而不是 PowerShell 会话/进程。

这里有几种方法可以让您考虑您的选择。

###############################################################################
#region Begin initialize environment                                          #
###############################################################################
    
    # Initialize GUI resources
    Add-Type -AssemblyName  System.Drawing,
                            PresentationCore,
                            PresentationFramework,
                            System.Windows.Forms,
                            microsoft.VisualBasic
    [System.Windows.Forms.Application]::EnableVisualStyles()
    
###############################################################################
#endregion End initialize environment                                         #
###############################################################################

# Prevent the MessageBox UI from closing until an entry is made
while (
    ($UserEntry = [Microsoft.VisualBasic.Interaction]::
    InputBox('Enter a Host/User', 'Add Item')) -eq ''
)
{
    [System.Windows.Forms.MessageBox]::
    Show(
        'Entry cannot be empty', 
        "Error on close" , 
        0, 
        [System.Windows.MessageBoxImage]::Error
    )
}
"You entered $UserEntry"

或用于更精细控制的完整自定义表单

# Initialize the form object
$form = New-Object System.Windows.Forms.Form

# Define form elements
$form.Text = 'Data Entry'

$txtUserInput           = New-Object system.Windows.Forms.TextBox
$txtUserInput.multiline = $false
$txtUserInput.width     = 120
$txtUserInput.height    = 20
$txtUserInput.location  = New-Object System.Drawing.Point(40,29)
$txtUserInput.Font      = 'Microsoft Sans Serif,10'

$form.controls.AddRange(@(
    $txtUserInput
    )
)

# Evaluate form events
$form.Add_Closing(
{
    param
    (
        $Sender,$Event
    )

    $result = [System.Windows.Forms.MessageBox]::Show(
                'Are you sure you want to exit?', 
                'Close', 
                [System.Windows.Forms.MessageBoxButtons]::YesNo
            )

    if ($result -ne [System.Windows.Forms.DialogResult]::Yes)
    {$Event.Cancel = $true}
})

# Start the form
$form.ShowDialog() | Out-Null

# Resource disposal
$form.Dispose()

推荐阅读