Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
优雅地停在Powershell中_Powershell_Powershell 2.0 - Fatal编程技术网

优雅地停在Powershell中

优雅地停在Powershell中,powershell,powershell-2.0,Powershell,Powershell 2.0,如何在PowerShell脚本中捕获和处理Ctrl+C?我知道我可以通过v2中的cmdlet通过包含对Powershell.Stop()方法的覆盖来实现这一点,但我找不到可在脚本中使用的模拟方法 我目前正在执行清理,但在取消脚本时需要执行其他工作(而不是运行到完成) 您可以使用上描述的方法 总结: 设置 然后使用 if($Host.UI.RawUI.KeyAvailable -and (3 -eq [int]$Host.UI.RawUI.ReadKey("AllowCtrlC,Inc

如何在PowerShell脚本中捕获和处理Ctrl+C?我知道我可以通过v2中的cmdlet通过包含对
Powershell.Stop()
方法的覆盖来实现这一点,但我找不到可在脚本中使用的模拟方法


我目前正在执行清理,但在取消脚本时需要执行其他工作(而不是运行到完成)

您可以使用上描述的方法

总结:

设置

然后使用

if($Host.UI.RawUI.KeyAvailable -and (3 -eq  
    [int]$Host.UI.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,NoEcho").Character))
try-catch最后说:

即使使用CTRL+C停止脚本,最终块也会运行。A最后 如果Exit关键字在Catch中停止脚本,则块也会运行 街区

请参见下面的示例。运行它并按ctrl-c取消它

试试看
{
while($true)
{
“工作……”
开始睡眠-秒1
}
}
最后
{
写主持人“结束工作”
}

$PSCmdlet
上还有一个
Stopping
属性可以用于此操作。

哇,这太疯狂了。最后,我只是在C#中将脚本重写为cmdlet,这样我就可以重写Stop()。这是真的,但最终将运行,不仅因为调用了Exit,而且还因为Try块成功。正如我在问题中指出的,当脚本被取消时,我需要执行额外的工作(而不是运行到完成)。@fatcat111使用布尔标志。例如,在
try
的末尾设置
$didcomlete=$true
,并在
中检查($didcomlete){Write Host“end work.”是否($didcomlete)}
最后
不幸的是,如果PowerShell控制台窗口关闭,则不会执行finally块。在停止远程PSSession invoke命令或作业时也会调用finally块<代码>停止
即使在根据停止时也是如此。可能重复
if($Host.UI.RawUI.KeyAvailable -and (3 -eq  
    [int]$Host.UI.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,NoEcho").Character))