batch-file - 用批处理检查进程是否正在回答
问题描述
: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
这不起作用,我认为错误级别是问题,但我无法解决。我想检查该过程是否正在回答。如果不是,我想在超时后再次检查该过程。
我提前感谢您的帮助。
解决方案
读取错误级别和退出代码:
几乎所有应用程序和实用程序在完成/终止时都会设置退出代码。设置的退出代码确实有所不同,通常
0
(false) 代码将表示成功完成。
…<BR> 当外部命令由 运行时CMD.EXE
,它将检测可执行文件的返回或退出代码并将其设置ERRORLEVEL
为匹配。在大多数情况下,它们与退出代码ERRORLEVEL
相同,但在某些情况下它们可能会有所不同。
它的退出代码如以下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
关键字显式设置)
==> 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
}
将以上内容重写为单行(使用别名),您可能会遇到以下情况:
- 未找到具有指定名称的进程
==> powershell -noprofile -c "try{$x=@(gps programm -EA Stop|? {-not $_.Responding});exit $x.Count} catch {exit 5000}"
==> echo errorlevel=%errorlevel%
errorlevel=5000
- 找到具有指定名称的进程并做出响应
==> powershell -noprofile -c "try{$x=@(gps cmd -EA Stop|? {-not $_.Responding});exit $x.Count} catch {exit 5000}"
==> echo errorlevel=%errorlevel%
errorlevel=0
- 找到一个具有指定名称的进程并且没有响应
==> powershell -noprofile -c "try{$x=@(gps HxOutlook -EA Stop|? {-not $_.Responding});exit $x.Count} catch {exit 5000}"
==> echo errorlevel=%errorlevel%
errorlevel=1
- 找到更多具有指定名称的进程并且没有响应
==> powershell -noprofile -c "try{$x=@(gps -EA Stop|? {-not $_.Responding});exit $x.Count} catch {exit 5000}"
==> echo errorlevel=%errorlevel%
errorlevel=4
请注意上述枚举的不完整性:我们可以想象运行多个具有指定名称的进程的场景,其中一些进程响应而其他进程没有响应。
(换句话说,发现和不响应 并不意味着不存在另一个同名的发现和响应......)
推荐阅读
- android - Android 上的 Firebase:DataSnapshot.getChildrenCount() 返回 0
- mongodb - 如何在 Mongo DB 中合并数组和文档字段
- powershell - 如何向 SharePoint 添加列以显示文件版本计数和这些版本总和的大小?
- python - Python代码的自动完成和文档
- gnuplot - Gnuplot 强制关闭,以十进制绘制数据 x 以整数绘制
- java - 为 Minecraft 改装设置工作区时出错
- javascript - 使用 javascript 将时间戳转换为 yyyy-mm-dd hh:mm:ss 格式
- repository - 我应该在哪里处理干净架构中的实体属性集合
- flutter - 如何向下扩展定位的 Container?
- python - 将命令传递给 KiTTY UI