gpt4 book ai didi

powershell - 输出某些格式的表格线颜色

转载 作者:行者123 更新时间:2023-12-03 00:27:56 25 4
gpt4 key购买 nike

我运行下面的代码,它的工作原理:

Get-ChildItem -Path T: -Filter *.pfx | ForEach-Object { 
Import-PfxCertificate -FilePath $_.FullName -CertStoreLocation Cert:\CurrentUser\My -Password ****** -Force -AsPlainText) -Exportable
} |
Format-Table -Property @{Label="Computador"; Expression={$env:computername}},
@{Label="Nome"; Expression={$_.FriendlyName}},
@{Label="Validade"; Expression={$_.NotAfter}},
@{Label="Impressão digital"; Expression={$_.Thumbprint}} -AutoSize

我正在尝试用过期的红色证书写每一行。
如果我尝试这样做:
Get-ChildItem -Path T: -Filter *.pfx | ForEach-Object { 
Import-PfxCertificate -FilePath $_.FullName -CertStoreLocation Cert:\CurrentUser\My -Password ****** -Force -AsPlainText) -Exportable
} |
Format-Table -Property @{Label="Computador"; Expression={$env:computername}},
@{Label="Nome"; Expression={$_.FriendlyName}},
@{Label="Validade"; Expression={$_.NotAfter}},
@{Label="Impressão digital"; Expression={$_.Thumbprint}} -AutoSize |
Out-String | Write-Host -ForegroundColor Red

所有行变为红色。
如果我尝试将$ _值传递给If,则控制台会说这是一个Null值。

有什么建议么?

我想做的解决方案由mklement0提供。如果有人有相同的问题,我将离开我在这里所做的工作:
Get-ChildItem -Path T: -Filter *.pfx | ForEach-Object {
Import-PfxCertificate -FilePath $_.FullName -CertStoreLocation Cert:\CurrentUser\My -Password ****** -Force -AsPlainText) -Exportable
} | Format-Table -Property @{Label="Computador"; Expression={$env:computername}}, @{Label="Nome"; Expression={$_.FriendlyName}}, @{Label="Validade"; Expression={$_.NotAfter}}, @{Label="Status"; Expression={if (($_.NotAfter).subtract([DateTime]::Now).days -lt 0){"Expirado"} elseif (($_.NotAfter).subtract([DateTime]::Now).days -lt 30){"Expirando"}}},@{Label="Impressão digital"; Expression={$_.Thumbprint}} -AutoSize | Out-String -Stream |
ForEach-Object {
$fgArg = if ($_ -match 'Expirado') { @{ 'BackgroundColor' = 'Red'; 'ForegroundColor' = 'Black'} } elseif ($_ -match 'Expirando') { @{ 'BackgroundColor' = 'Yellow'; 'ForegroundColor' = 'Black'} } else { @{} }
Write-Host @fgArg $_
}

最佳答案

关键是使用 Out-String-Stream开关启用逐行处理;默认情况下,Out-String输出单个多行字符串。

这是一个简单的示例,将包含子字符串expired的行涂成红色(与PowerShell中一样,默认情况下,匹配不区分大小写):

'A valid certificate', 'An expired certificate', 'A valid certificate' | 
Out-String -Stream | ForEach-Object {
$fgArg = if ($_ -match 'expired') { @{ 'ForegroundColor' = 'Red' } } else { @{} }
Write-Host @fgArg $_
}

以上 yield :

enter image description here

如果您正在寻找打包为高级功能的此功能,请参见function
我的 this answer中的 Out-HostColored

关于powershell - 输出某些格式的表格线颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51564131/

25 4 0
文章推荐: unity3d - 上传音频文件时统一显示音频频谱(波形)
文章推荐: javascript - 如何在 fs 文本文件中进行换行以进行记录
文章推荐: javascript - 如何迭代选定的