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

如何为PowerShell中PSCustomObject的布尔结果添加颜色显示?

PowerShell 表格布尔值着色实现方案

需要让PowerShell输出的表格中,IsMember列的True显示绿色,False显示红色,尝试过额外的foreach循环但未成功,以下是最佳实现方法。

修改后的完整代码

while($true){
    $UserID = Read-Host -Prompt 'UserID'
    
    $GroupNames = @("WHfB","LongName345","Some-Group2","Group","Example123","Another-One21")
    
    $Prompt = 'net user '+$UserID+' /domain'
    $Result = cmd.exe /c $Prompt
    
    Write-Host "`n`nTrue  =`tMember of Group;`nFalse =`tNO Member of Group;`n`n"
    
    $Table = foreach ($item in $GroupNames){
        [PSCustomObject]@{
            GroupName = $item
            IsMember = [bool]($Result -match $item)
        }
    }

    # 输出带颜色的表格内容
    Write-Host "GroupName`t`tIsMember" -ForegroundColor Cyan
    Write-Host "---------`t`t--------" -ForegroundColor Cyan
    foreach ($row in $Table) {
        $textColor = $row.IsMember ? 'Green' : 'Red'
        # 处理组名长度,保证对齐
        $formattedGroupName = $row.GroupName.PadRight(16)
        Write-Host "$formattedGroupName`t$($row.IsMember)" -ForegroundColor $textColor
    }

    pause
}

关键说明

  • 直接使用Format-Table无法实现单元格级的颜色自定义,因此改用Write-Host手动构建表格输出。
  • 根据IsMember的布尔值动态切换前景色:True用绿色,False用红色。
  • 通过PadRight方法统一组名的显示长度,让表格对齐更规整。

内容的提问来源于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 19:35:02