![](/img/trans.png)
[英]Powershell: Properly coloring Get-Childitem output once and for all
[英]Coloring output
我做了一個非常簡單的代碼,只檢查幾個 regkeys。 然而,為了讓它對眼睛更友好,我希望每當它是 False 時我可以將其設為紅色,而每當它是 True 時我可以將其設為綠色。
我在谷歌上搜索了很多關於這個但找不到我想要完成的明確解決方案。 非常感謝任何提示。
Write-Host "Update Pending" -ForegroundColor Cyan
Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Services\Pending'
""
Write-Host "Reboot Pending:" -ForegroundColor Cyan
Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending'
""
Write-Host "Reboot Required:" -ForegroundColor Cyan
Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'
""
Write-Host "Pending File Rename Operations:" -ForegroundColor Cyan
Test-Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations'
""
Write-Host "Beschikbare Updates:" -ForegroundColor Cyan
Test-Path 'HKLM:\SOFTWARE\Microsoft\Updates\UpdateExeVolatile'
將 output 從Test-Path
保存到變量中,使用該值指定一種顏色或另一種顏色作為參數傳遞給Write-Host
:
Write-Host "Update Pending" -ForegroundColor Cyan
$testResult = Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Services\Pending'
Write-Host $testResult -ForegroundColor @('Red', 'Green')[$testResult]
Write-Host ''
PowerShell 將在數組索引器中使用時將$False
隱式轉換為0
並將$True
轉換為 1,因此$False
會導致選擇'Red'
。
由於您基本上每次都在重復相同的測試操作,因此您可以通過將標簽和注冊表項組織到哈希表中來簡化代碼,然后只編寫要測試的代碼和 output 一次:
$testCases = [ordered]@{
"Update Pending" = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Services\Pending'
"Reboot Pending" = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending'
"Reboot Required" = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'
"Pending File Rename Operations" = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations'
"Beschikbare Updates" = 'HKLM:\SOFTWARE\Microsoft\Updates\UpdateExeVolatile'
}
foreach($label in $testCases.psbase.Keys){
Write-Host "${label}:" -ForegroundColor Cyan
$testResult = Test-Path $testCases[$label]
Write-Host $testResult -ForegroundColor @('Red','Green')[$testResult]
Write-Host ''
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.