how to get process id of a running process as show

2019-02-28 12:35发布

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?

2条回答
我只想做你的唯一
2楼-- · 2019-02-28 12:43

select just pid for notepad process :

 Get-Process -Name chrome | select Id | Format-List

for get stamps from your job run it just

Get-Job | select ID | Format-List

output

Id : 2
查看更多
你好瞎i
3楼-- · 2019-02-28 12:50

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 from Start-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 and 52 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 TechNet

However

Why are you using Start-Job? Is this part a greater script? You should just be able to use Invoke-Command as pass it the scriptblock $cmd.

$cmd = {
  param($abc)
  Write-Host $abc
}

$processes = Get-Process -Name notepad | Select -ExpandProperty ID 
foreach ($process in $processes){ 
    Invoke-Command -ScriptBlock $cmd -ArgumentList $process
}

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 calling Write-Output instead.

查看更多
登录 后发表回答