0

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.

nikkatsa
  • 1,751
  • 4
  • 26
  • 43

1 Answers1

1

$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

(...)
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
  • Thank you Shay Levy. You are absolutely right. I didn't realize that i was passing the array in the variable, as i was printing it and i could only see one value (because i was only passing one value. Stupid me). And i will change the Get-Process to use the -Id as it is much cleaner. Thanks a lot. – nikkatsa Dec 03 '13 at 10:19