I have a windows Powershell script that includes the following line...
$script:parent = (Get-Process -Id (Get-CimInstance Win32_Process -Filter "ProcessID = $pid").ParentProcessId).Name
The line appears twice in the same script. The first time it gets executed it always works fine and returns either svchost, explorer or powershell (meaning that the script was either started by task scheduler, a shortcut on the desktop, or another powershell script).
The second time it's executed, it mostly works fine (and returns the same result) but occasionally returns the following...
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
Why is it failing the 2nd time?
(BTW - I'm asking this out of curiosity only, there's a simple fix - only execute the command the one time!)
UPDATE - @mklement0 answer is correct. I hadn't spotted a critical fact, the second execution of 'who's the parent' only ever fails if the parent was a powershell script. The script runs 24*7 and is designed that in the event of a critical failure it will re-start another copy of itself and then exit. Since this only occurs once or twice a month I had forgotten about this feature
(Get-Process -Id $pid).Parentis only supported in PowerShell (Core) 7, not also in Windows PowerShell.