【问题标题】:How can I start a process, pause for 2 hours and then kill a process in Powershell如何启动一个进程,暂停 2 小时,然后在 Powershell 中终止一个进程
【发布时间】:2017-05-24 15:29:46
【问题描述】:

如何在 Powershell 中启动一个进程,暂停 2 小时然后终止一个进程。我可以让它启动进程并终止进程,但 Start-Sleep 命令似乎在我的脚本中不起作用。我以为这很简单。不知道我是否遗漏了什么,或者这是否可以睡 2 个小时。

if((Get-Process -Name test -ErrorAction SilentlyContinue) -eq $null){
."C:\Program Files (x86)\test.exe" Start-Sleep -s 7200 Stop-Process -name test}

【问题讨论】:

  • 你的脚本有换行符吗?如果不是,则 Start-Sleep 和其余部分将作为参数传递给 test.exe。 test.exe 是否独立启动?您可能需要 start-process ...test.exe 在单独的进程中运行它。
  • 我也会考虑这样的计划任务,这样您就不必担心 PowerShell 窗口。您还可以为此设置执行限制。

标签: powershell


【解决方案1】:

只是在 Jeff 的回答中添加一些内容 - 您可以使用 Start-Process-PassThru 来确保您正在结束您启动的正确进程。

if ((Get-Process 'test' -EA SilentlyContinue) -eq $null){
    $Process = Start-Process "C:\Program Files (x86)\test.exe" -PassThru
    Start-Sleep -Seconds (2*60*60)
    $Process | Stop-Process
}

这意味着如果进程因其他原因终止并手动或通过脚本的另一个副本等重新启动,则该脚本不会在两小时后终止它,而是会终止正确的进程。

【讨论】:

    【解决方案2】:

    在单行脚本块中放置多个 PowerShell 命令时,必须用分号分隔命令:

    if((Get-Process -Name test -ErrorAction SilentlyContinue) -eq $null){ ."C:\Program Files (x86)\test.exe" ; Start-Sleep -s 7200 ; Stop-Process -name test}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      • 2014-05-03
      相关资源
      最近更新 更多