如何启动一个进程,暂停 2 小时,然后在 Powershell 中终止一个进程



如何启动一个进程,暂停 2 小时,然后在 Powershell 中终止一个进程。 我可以让它启动进程并终止进程,但 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}

只是为了给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
}

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

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

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