Question

I have a problem with the Get-Process command in Powershell, when i use it inside a Job.

I would like to get a process by PID, so i am doing the below:

$MyProcess = Get-Process | Where-Object { $_.Id -eq $parentProcessID }

The above, when it is called as a command from a Powershell script, returns me the process expected.

If I use the exact same command inside a Start-Job{} block then it gives me null, even for a process that is running. For example:

Start-Job {
$parentProcessID = $args
$MyProcess = Get-Process | Where-Object { $_.Id -eq $parentProcessID }
if($MyProcess -eq $null)
{
    echo "Nothing returned"
}
} -ArgumentList "$parentProcessID"

Is there anything i am missing here? Has anyone run into similar situation before?

Any insights appreciated.

Thanks.

Was it helpful?

Solution

$args is an array, if you still want to use make sure to pick its first element:

$parentProcessID = $args[0]

Also, Get-Process has an Id parameter, there's no need to use the Where-Object cmdlet:

Get-Process -Id $parentProcessID 

Another avantage of the Id parameter is that it takes an array of Id's so it would have work if you passes to it the value of $args as is.

You can also use names parameters for the scriptblock instaed of using $args:

Start-Job {
    param([int[]]$procid)

    $MyProcess = Get-Process -Id $procid

(...)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top