Write-Warning

Getting to Know Write-Warning in PowerShell

Welcome back to Wahmans Powershell blog! Today, we’re diving into a handy cmdlet that helps scripts communicate effectively: Write-Warning.

What does it do?
According to Microsoft, Write-Warning “Writes a warning message.” Simple enough, but don’t be fooled by how basic that sounds. These messages are a great way to alert users when something is off, even if it’s not a fatal error.

Why Use Write-Warning?

When writing scripts, not every issue should halt execution. Sometimes you want to give users—and yourself—a heads-up. Write-Warning lets you surface such messages without triggering errors or breaking the flow.

Let’s look at four examples, ranging from beginner to more advanced usage:

Example 1: Basic Use (Beginner)

Write-Warning "Disk space is low!"

This simply outputs a warning with yellow text. Great for when you want to make the message stand out during script runs.

Example 2: Conditional Check (Intermediate)

$freeSpace = 5
if ($freeSpace -lt 10) {
    Write-Warning "Warning: Free space is below 10GB."
}

Here we’re using Write-Warning in a conditional scenario—only when a specific condition is met does the user get warned.

Example 3: Function with a Warning (Advanced)

function Remove-ItemSafely {
    param (
        [Parameter(Mandatory)]
        [string]$Path
    )

    if (-not (Test-Path $Path)) {
        Write-Warning "Path '$Path' does not exist. Nothing will be deleted."
        return
    }

    Remove-Item -Path $Path -Recurse -Force
}

This example adds robust user communication to a function, warning when the path doesn’t exist rather than throwing an error immediately.

Example 4: Logging and Warnings (Advanced)

function Start-SystemCheck {
    $cpuUsage = Get-Counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 1 -MaxSamples 3 | 
        Select-Object -ExpandProperty CounterSamples | 
        Select-Object -ExpandProperty CookedValue | 
        Measure-Object -Average | 
        Select-Object -ExpandProperty Average

    if ($cpuUsage -gt 80) {
        Write-Warning "CPU usage is high: $([math]::Round($cpuUsage, 2))%"
    }
    else {
        Write-Output "CPU usage is within normal range: $([math]::Round($cpuUsage, 2))%"
    }
}

In this advanced example, we perform a system check and provide a warning if CPU usage exceeds 80%. It demonstrates combining data gathering, logic, and user-friendly feedback.

Wrap-Up

Write-Warning is a powerful cmdlet when you want to increase the readability and usability of your scripts by offering meaningful and non-intrusive feedback. Whether you’re a PowerShell beginner or writing enterprise-level automation, using warnings the right way can significantly improve the user experience.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *