如何在不中断脚本本身的情况下中断脚本中调用的可执行文件?

时间:2016-01-05 11:47:28

标签: powershell

我们假设您将以下脚本保存在文件outermost.ps1中:

powershell.exe -Command "while ( 1 -eq 1 ) {} "
echo "Done"

运行outermost.ps1时,您只能通过按 Ctrl + C 中止此操作,并且不会将任何输出写入控制台。当按下 Ctrl + C 时,如何修改它以便最外面的脚本继续并执行echo "Done"

这是现实场景的简化版本,其中内部脚本实际上是一个可执行文件,只能通过按 Ctrl + C 来停止。

编辑:脚本也可以是:

everlooping.exe
echo "Done"

但是我想提供一个例子,每个人都可以复制粘贴到编辑器中,如果他们想在家里尝试#34;。

2 个答案:

答案 0 :(得分:4)

job启动无限命令/语句,将PowerShell脚本进程 Ctrl + C 作为常规输入(参见here) ,并在收到输入时停止工作:

[Console]::TreatControlCAsInput = $true

$job = Start-Job -ScriptBlock {
  powershell.exe -Command "while ( 1 -eq 1 ) {} "
}

while ($true) {
  if ([Console]::KeyAvailable) {
    $key = [Console]::ReadKey($true)
    if (($key.Modifiers -band [ConsoleModifiers]::Control) -and $key.Key -eq 'c') {
      $job.StopJob()
      break
    }
  }
  Start-Sleep -Milliseconds 100
}

Receive-Job -Id $job.Id
Remove-Job -Id $job.Id

echo "Done"

如果您需要在作业运行时从作业中检索输出,您可以在else分支中对外部if语句执行此操作:

if ($job.HasMoreData) { Receive-Job -Id $job.Id }

答案 1 :(得分:0)

最简单的解决方案是:

    Start-Process -Wait "powershell.exe" -ArgumentList "while ( 1 -eq 1 ) {}"
    echo "Done"

这将生成第二个窗口unlinke ansgar-wiechers solution,但用最少量的代码解决了我的问题。

感谢Jaqueline Vanek的提示

相关问题