PowerShell脚本中获取父进程代码首次正常二次偶发失败原因咨询
问题:PowerShell脚本中获取父进程命令偶发失败的原因
场景与代码
我有一个7*24运行的Windows PowerShell脚本,其中包含以下代码:
$script:parent = (Get-Process -Id (Get-CimInstance Win32_Process -Filter "ProcessID = $pid").ParentProcessId).Name
这段代码在脚本中出现两次。
执行现象
- 首次执行时始终正常,返回值根据启动方式不同为
svchost(任务计划程序启动)、explorer(桌面快捷方式启动)或powershell(其他PowerShell脚本启动)。 - 第二次执行时大多正常,但偶尔会抛出如下错误:
Get-Process : Cannot find a process with the process identifier 17216.
At C:\blah\blah\testscript.ps1:2675 char:23
- ... t:parent = (Get-Process -Id (Get-CimInstance Win32_Process -Filter "P ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- CategoryInfo : ObjectNotFound: (17216:Int32) [Get-Process], ProcessCommandException
- FullyQualifiedErrorId : NoProcessFoundForGivenId,Microsoft.PowerShell.Commands.GetProcessCommand
故障触发条件
仅当父进程为powershell脚本时,第二次执行才会失败。另外脚本故障时会自动重启自身并退出,这个特性之前被忽略。
疑问
现咨询该偶发失败的原因(注:仅出于好奇咨询,已有简单修复方案:仅执行一次该命令)
内容的提问来源于stack exchange,提问作者ConanTheGerbil
相关产品推荐
相关产品推荐

