Jac*_*ack 7 powershell process instances
有关如何编写返回进程实例数的函数的任何想法都在运行?
也许是这样的?
function numInstances([string]$process)
{
$i = 0
while(<we can get a new process with name $process>)
{
$i++
}
return $i
}
Run Code Online (Sandbox Code Playgroud)
编辑:开始编写一个函数...它适用于单个实例但如果运行多个实例则会进入无限循环:
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
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*att 13
function numInstances([string]$process)
{
@(get-process -ea silentlycontinue $process).count
}
Run Code Online (Sandbox Code Playgroud)
编辑:添加静默继续和数组强制转换为零和一个进程.
这对我有用:
function numInstances([string]$process)
{
@(Get-Process $process -ErrorAction 0).Count
}
# 0
numInstances notepad
# 1
Start-Process notepad
numInstances notepad
# many
Start-Process notepad
numInstances notepad
Run Code Online (Sandbox Code Playgroud)
输出:
0
1
2
Run Code Online (Sandbox Code Playgroud)
虽然这很简单但是在这个解决方案中有两个重点:1)使用-ErrorAction 0
(0 SilentlyContinue
与之相同),因此当没有指定的进程时它可以很好地工作; 2)使用数组运算符,@()
以便在有单个流程实例时它可以工作.
使用内置cmdlet组对象更容易:
get-process | Group-Object -Property ProcessName
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21800 次 |
最近记录: |