powershelltext-coloring

Coloring output


I made a very very simple code that just checks a few regkeys. However to make it more nice to the eyes I was hoping that whenever it's False i can make it red and whenever it's True i can make it green.

I googled a bunch about this but couldn't find a clear solution for what i'm trying to accomplish. Any tips are very much appreciated.

    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'

Solution

  • Save the output from Test-Path to a variable, the use the value to specify one color or the other to pass as an argument to 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 will implicitly convert $False to 0 and $True to 1 when used in an array indexer, so $False results in 'Red' being picked.


    Since you're basically repeating the same test operation every time, you can simplify your code by organizing the labels and registry keys into a hashtable and then only write the code to test and output once:

    $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 ''
    }