I am learning powershell and trying to see how can variables and functions could be used. I want to print out PID for all running notepad instances, basically what is shown in PID column under Details tab in Task manager. I have written following code
$cmd = {
param($abc)
Write-Host $abc
}
$processes = Get-Process -Name notepad | Select -ExpandProperty ID
foreach ($process in $processes)
{
Start-Job -ScriptBlock $cmd -ArgumentList $process
}
I am getting following result.
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
50 Job50 BackgroundJob Running True localhost ...
52 Job52 BackgroundJob Running True localhost ...
Two issues here.
1. I only want PID, it has whole lot.
2. I expect that Id in above output is the PID but what is shown in task manager is very differnt.
Can you tell me what am I doing wrong?
select just pid for notepad process :
for get stamps from your job run it just
output
PID vs ID
You are getting the PID's that you expect in
$processes
just fine. The issue here is that you are seeing the output fromStart-Job
and confusing its Job ID with your PID output.You have 2 notepad.exe's running in your example so PowerShell, as requested, runs 2 jobs. The ID
50
and52
are just the id assigned to the jobs. To get the output you are looking for you first need to capture it.If at the end of your script you put
Get-Job | Receive-Job
you would have seen the PID's you were expecting. For more reading on jobs and job output you can find a great article on TechNetHowever
Why are you using
Start-Job
? Is this part a greater script? You should just be able to useInvoke-Command
as pass it the scriptblock$cmd
.Warning
While this is not an issue in the PowerShell 5.0 you are using
Write-Host
for output in you example. If you need to use that output in another function you should consider callingWrite-Output
instead.