powershell - Try.. catch.. 最终在 Read-Host 期间失败
问题描述
当脚本执行Read-Host
cmdlet 时,关闭窗口不会激活finally
块。下面是一个任意但功能最少的示例。我正在使用 PowerShell 5.0。Beep() 只是为了让 finally 块的执行显而易见。
try {
$value= Read-Host -Prompt "Input"
sleep 5
} finally {
[Console]::Beep(880,1000)
}
- 如果您在
Read-Host
该finally
块不会执行期间通过单击红色 X 来关闭窗口。 - 如果在
sleep
块finally
将执行期间通过单击红色 X 关闭窗口。 - 如果您在任何时候使用 Ctrl-C 中断,该
finally
块将执行。
finally
关于为什么在 a 期间关闭窗口时块没有执行,我是否缺少一些基本的东西Read-Host
?
完整案例涉及在 Amazon Snowball 设备上启动服务,如果脚本关闭则需要停止服务。完整的案例行为反映了上面的示例案例。
编辑:由于评论说 $input 是保留变量,将变量从 $input 更改为 $value。不改变行为。
解决方案
继续我的评论。
控制台主机有点不灵活,具体取决于您在本机上所做的事情。该“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()
推荐阅读
- excel - 用户表单组合框,我可以在其中根据单元格颜色编码添加或删除项目
- elasticsearch - 通过环境变量(docker)配置elasticsearch
- bash - 终端启动问题
- django - /fileupload/ 处的 NoReverseMatch :未找到“视图”的反向。“视图”不是有效的视图函数或模式名称
- java - 如何在java中的main方法之后执行静态块?
- javascript - 将日期最小值设置为始终比当前日期早 10 天
- java - Android DownloadManager 在某些情况下不起作用
- php - 在 PHP Session 中存储复选框并回显它
- python - 如何在不使用arcpy的情况下处理python中不支持的fiona类型?
- amazon-web-services - How to connect a machine on VPN to AWS PHZ DNS?