我目前想检查进程列表是否正在运行,然后在表中显示结果,例如:
Process Status
======= ======
Process 1 Running
Process 2 Not Running
Process 3 Running
我有下面的代码,它产生一个输出,将每个输入和输出显示为一个字符串,但它看起来很困惑,具体取决于进程名称的长度。
$Node = Read-Host -Prompt 'Input Node name'
$Process = @("Process1", "Process2", "Process3")
$Process | foreach-object {if(!(Get-Process -Name $_ -ComputerName $Node - ErrorAction SilentlyContinue)) {"$_ - Not Running"} else {"$_ - Running"}}
我很茫然。所有帮助表示赞赏。
最佳答案
最好(更快)进行单个远程调用来获取所有进程,而不是每个进程一个,所以这样做并存储所有结果 - 至少是进程的名称。
下一部分是非平凡的。 PowerShell 和格式整齐的表格的工作方式是为每个表格行创建一个对象(所有东西的捆绑),每个对象具有每个列名称的属性。
# Processes to look for
$Process = @("Process1", "Process2", "Process3")
$Node = Read-Host -Prompt 'Input Node name'
# Get running processes, and only keep their names
$runningProcesses = Get-Process -ComputerName $Node -ErrorAction SilentlyContinue |
Select-Object -ExpandProperty Name
$Process | ForEach-Object {
# For each process name to look for, generate a hashtable of
# columns and their values,
# then cast it into a PS Object
[PSCustomObject]@{
'ProcessName' = $_
'Status' = if ($runningProcesses -contains $_) { "Running" } else { "Not Running" }
}
}
这提供了一个整洁的格式化表格输出,并且也是结构化数据,因此您可以将其输出提供给
| ForEach-Object { $_.Status }
并按名称挑选出各个部分,这是您使用字符串格式方法无法做到的。
关于powershell - foreach 的输入和输出到表中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50172754/