检查批处理过程是否正在应答

Check with batch if the process is answering or not

:loop
>nul timeout /t 600 /nobreak
powershell -ExecutionPolicy Unrestricted -c "Get-Process -Name programm | Where-Object -FilterScript {$_.Responding -eq $false}"
if not errorlevel 1 goto loop

这不起作用,我认为错误级别是问题所在,但我无法解决。 我想检查进程是否正在回答。如果不是我想在超时后再次检查该过程。

在此先感谢您的帮助。

阅读Errorlevel and Exit codes:

Almost all applications and utilities will set an Exit Code when they complete/terminate. The exit codes that are set do vary, in general a code of 0 (false) will indicate successful completion.

When an external command is run by CMD.EXE, it will detect the executable's Return or Exit Code and set the ERRORLEVEL to match. In most cases the ERRORLEVEL will be the same as the Exit code, but there are some cases where they can differ.

PowerShell 退出代码 如下例所示:

  • 未成功完成 ( errorlevel 1 ):
==> powershell -noprofile -c "Get-Process -Name invalid_programm"
Get-Process : Cannot find a process with the name "invalid_programm". Verify the process name and call the cmdlet again.
At line:1 char:1
+ Get-Process -Name invalid_programm
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (invalid_programm:String) [Get-Process],ProcessCommandException
    + FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand

==> echo errorlevel=%errorlevel%
errorlevel=1
  • 成功完成 ( errorlevel 0 )
==> powershell -noprofile -c "return 1"
1

==> echo errorlevel=%errorlevel%
errorlevel=0
  • 成功完成errorlevel使用exit keyword明确设置)
==> powershell -noprofile -c "exit 2"

==> echo errorlevel=%errorlevel%
errorlevel=2

因此,您可以使用以下代码片段(应该始终成功完成):

try { 
    $x = @(Get-Process -Name programm -ErrorAction Stop | 
             Where-Object -FilterScript {-not $_.Responding})
    exit $x.Count
} catch { 
    exit 5000          # or other `absurd` value
}

将上面改写成一行(使用别名),你可能会遇到以下场景:

  1. 具有指定名称的进程未找到
==> powershell -noprofile -c "try{$x=@(gps programm -EA Stop|? {-not $_.Responding});exit $x.Count} catch {exit 5000}"

==> echo errorlevel=%errorlevel%
errorlevel=5000
  1. 具有指定名称的进程找到并响应
==> powershell -noprofile -c "try{$x=@(gps cmd -EA Stop|? {-not $_.Responding});exit $x.Count} catch {exit 5000}"

==> echo errorlevel=%errorlevel%
errorlevel=0
  1. 一个具有指定名称的进程找到但没有响应
==> powershell -noprofile -c "try{$x=@(gps HxOutlook -EA Stop|? {-not $_.Responding});exit $x.Count} catch {exit 5000}"

==> echo errorlevel=%errorlevel%
errorlevel=1
  1. 更多具有指定名称的进程找到但没有响应
==> powershell -noprofile -c "try{$x=@(gps -EA Stop|? {-not $_.Responding});exit $x.Count} catch {exit 5000}"

==> echo errorlevel=%errorlevel%
errorlevel=4

请注意以上枚举的不完整性:我们可以想象场景,其中运行更多具有指定名称的进程,其中一些响应而另一些不响应。
(换句话说,找到但未响应 并不意味着不存在另一个找到&响应同名...)