You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PowerShell foreach的输入输出整理为表格列展示进程状态

Fixing Process Status Table Formatting in PowerShell

Got it, let's fix that messy process status output in PowerShell! The issue with your current code is that you're outputting raw strings without any alignment control—here are two solid solutions to get that clean, consistent table you want:

Method 1: Use PowerShell's Built-in Format-Table (Auto-Aligned)

This approach leverages PowerShell's native object handling to automatically align columns perfectly, even if process names vary in length:

$Node = Read-Host -Prompt 'Input Node name'
$ProcessList = @("Process1", "Process2", "Process3")

# Gather process statuses into structured objects
$processStatuses = $ProcessList | ForEach-Object {
    [PSCustomObject]@{
        Process = $_
        Status  = if (Get-Process -Name $_ -ComputerName $Node -ErrorAction SilentlyContinue) {
            'Running'
        } else {
            'Not Running'
        }
    }
}

# Output a clean, auto-sized table
$processStatuses | Format-Table -AutoSize

How it works:

By creating PSCustomObject instances, you give PowerShell clear column definitions. Format-Table -AutoSize then adjusts each column's width to fit the longest entry, so everything lines up neatly without manual tweaking.

Method 2: Manual String Formatting (Fixed Column Widths)

If you prefer precise control over column widths (e.g., to match a specific layout), use PowerShell's string formatting operator (-f) to enforce alignment:

$Node = Read-Host -Prompt 'Input Node name'
$ProcessList = @("Process1", "Process2", "Process3")

# Print aligned headers (adjust the number of dashes to match column widths)
Write-Host "Process       Status"
Write-Host "=======       ======"

$ProcessList | ForEach-Object {
    $status = if (Get-Process -Name $_ -ComputerName $Node -ErrorAction SilentlyContinue) {
        'Running'
    } else {
        'Not Running'
    }
    # Format string: first column left-aligned (12 characters), second column left-aligned
    Write-Host ("{0,-12} {1}" -f $_, $status)
}

How it works:

The {0,-12} syntax tells PowerShell to left-align the first value (process name) and reserve 12 characters for it—any shorter names will get padded with spaces, ensuring the status column starts at the same position every time. Adjust the 12 value if you have longer process names.

内容的提问来源于stack exchange,提问作者Ryan Clayton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:00:51