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

如何实现PowerShell脚本输出中布尔值与组名的对齐显示?

优化PowerShell脚本输出对齐的最佳方法

我正在优化PowerShell脚本的输出格式以提升可读性,当前结果正确但排版不佳。由于各组名长度不同,使用制表符`t也无法让True/False布尔值对齐,期望实现如下示例中的对齐效果:

WHfB              True
M365Outlook       False
M365-Admin        False
Mobile Apps       True
O365-Pilot        False
M365-Teams-User   True

当前使用的脚本代码:

$UserID = Read-Host -Prompt 'UserID'

$GroupNames = @("WHfB","M365Outlook","M365-Admin","Mobile Apps","O365-Pilot","M365-Teams-User")

$Prompt = 'net user '+$UserID+' /domain'
$Result = cmd.exe /c $Prompt

echo "True  =`tMember of the Group;`nFalse =`tNO Member of the Group;`n`n"

ForEach ($item in $GroupNames){
$TrueFalse = [bool]($Result -match $item)
echo "$item = $TrueFalse"
}
echo `n`n
pause

请问最简单/最佳的实现方法是什么?


方法1:格式化字符串指定固定宽度(最简单)

直接修改循环内的输出逻辑,用PowerShell的格式化操作符-f给组名分配固定宽度,让布尔值自动对齐:

ForEach ($item in $GroupNames){
    $TrueFalse = [bool]($Result -match $item)
    # 左对齐组名,占用20个字符宽度,不足补空格
    Write-Host ("{0,-20} {1}" -f $item, $TrueFalse)
}

这里{0,-20}表示第一个参数($item)左对齐,占20个字符位,最长的组名"M365-Teams-User"长度为16,设为20留足余量刚好。如果后续组名更长,只需调整数字即可。

方法2:自定义对象+Format-Table(更灵活)

如果需要结构化数据或后续扩展输出,可先创建自定义对象再格式化:

$output = @()

ForEach ($item in $GroupNames){
    $TrueFalse = [bool]($Result -match $item)
    $output += [PSCustomObject]@{
        GroupName = $item
        IsMember = $TrueFalse
    }
}

# 指定列宽输出
$output | Format-Table -Property @{Name='GroupName'; Width=20}, IsMember -AutoSize

这种方式把输出数据结构化,不仅对齐整齐,还方便后续导出到CSV或做其他数据处理。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 17:55:00