检测以相同名称运行的进程数
关于如何编写一个返回正在运行的进程的实例数的函数有什么想法吗?
也许是这样的?
function numInstances([string]$process)
{
$i = 0
while(<we can get a new process with name $process>)
{
$i++
}
return $i
}
编辑:开始编写一个函数...它适用于单个实例,但如果多个实例正在运行,它就会进入无限循环:
function numInstances([string]$process)
{
$i = 0
$ids = @()
while(((get-process $process) | where {$ids -notcontains $_.ID}) -ne $null)
{
$ids += (get-process $process).ID
$i++
}
return $i
}
Any ideas of how to write a function that returns the number of instances of a process is running?
Perhaps something like this?
function numInstances([string]$process)
{
$i = 0
while(<we can get a new process with name $process>)
{
$i++
}
return $i
}
Edit: Started to write a function... It works for a single instance but it goes into an infinite loop if more than one instance is running:
function numInstances([string]$process)
{
$i = 0
$ids = @()
while(((get-process $process) | where {$ids -notcontains $_.ID}) -ne $null)
{
$ids += (get-process $process).ID
$i++
}
return $i
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
编辑:添加了静默继续和数组转换以与零个和一个进程一起使用。
EDIT: added the silently continue and array cast to work with zero and one processes.
这对我有用:
输出:
虽然很简单,但此解决方案中有两个要点:1)使用
-ErrorAction 0
(0 与SilentlyContinue
相同),所以当没有指定的流程时它可以很好地工作; 2) 使用数组运算符@()
,以便它在只有单个流程实例时起作用。This works for me:
Output:
Though it is simple there are two important points in this solution: 1) use
-ErrorAction 0
(0 is the same asSilentlyContinue
), so that it works well when there are no specified processes; 2) use the array operator@()
so that it works when there is a single process instance.使用内置的 cmdlet 组对象要容易得多:
Its much easier to use the built-in cmdlet group-object:
有一个很好的单行:
(ps).count
There is a nice one-liner :
(ps).count
(Get-Process |Where-Object {$_.Name -eq 'Chrome'}).count
这将返回正在运行的同名进程的数量。您可以添加过滤器以进一步格式化数据。
(Get-Process | Where-Object {$_.Name -eq 'Chrome'}).count
This will return you the number of processes with same name running. you can add filters to further format your data.