如何获取正在运行的进程的进程 ID,如任务管理器中所示 [英] how to get process id of a running process as shown in task manager
问题描述
我正在学习 powershell 并试图了解如何使用变量和函数.我想打印出所有正在运行的记事本实例的 PID,基本上是任务管理器中详细信息选项卡下的 PID 列中显示的内容.我写了以下代码
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
}
我得到以下结果.
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
50 Job50 BackgroundJob Running True localhost ...
52 Job52 BackgroundJob Running True localhost ...
这里有两个问题.
1.我只想要PID,它有很多.
2. 我希望上面输出中的 Id 是 PID,但任务管理器中显示的内容非常不同.
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?
推荐答案
PID vs ID
您在 $processes
中获得了您期望的 PID.这里的问题是您看到了 Start-Job
的输出,并将其 Job ID 与您的 PID 输出混淆.
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.
您的示例中有 2 个 notepad.exe 正在运行,因此 PowerShell 根据要求运行 2 个作业.ID 50
和 52
只是分配给作业的 ID.要获得您正在寻找的输出,您首先需要捕获它.
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.
如果您在脚本的末尾放置了 Get-Job |Receive-Job
你会看到你期望的PID.有关作业和作业输出的更多信息,您可以在 TechNet
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
你为什么使用Start-Job
?这部分是一个更大的脚本吗?您应该能够使用 Invoke-Command
将脚本块 $cmd
传递给它.
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
}
警告
虽然这在 PowerShell 5.0 中不是问题,但您在示例中使用 Write-Host
进行输出.如果您需要在另一个函数中使用该输出,则应考虑改为调用 Write-Output
.
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.
这篇关于如何获取正在运行的进程的进程 ID,如任务管理器中所示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!