输入和输出foreach到表中的列

Rya*_*ton 4 powershell

我目前想检查进程列表是否正在运行,然后在表中显示结果,例如:

 Process        Status
 =======        ======
Process 1       Running
Process 2      Not Running
Process 3       Running
Run Code Online (Sandbox Code Playgroud)

我有下面的代码生成一个输出显示每个输入和输出为一个字符串,但它看起来很乱,取决于进程名称的长度.

$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"}}
Run Code Online (Sandbox Code Playgroud)

我很茫然.所有帮助赞赏.

Tes*_*ler 5

更好(更快)进行单个远程调用以获取所有进程,而不是每个进程一个,所以这样做并存储所有结果 - 至少是进程的名称.

下一部分是非平凡的.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" }

    }

}
Run Code Online (Sandbox Code Playgroud)

这提供了一个整洁的格式化表输出,也是结构化数据,因此您可以将其输出提供给| ForEach-Object { $_.Status }并按名称选择各个部分,这是您不能用字符串格式化方法完成的.