Write-Output

Understanding the Power of Write-Output in PowerShell

Welcome back to Wahmans Powershell blog! Today, we’re taking a close look at a fundamental, yet sometimes misunderstood cmdlet: Write-Output. According to Microsoft’s documentation, the Write-Output cmdlet “writes the specified objects to the pipeline.” This makes it an essential cmdlet for script output, debugging, logging, and working within PowerShell’s object-oriented pipeline.

Let’s break it down and look at four examples to illustrate its usage — from beginners learning the ropes, to advanced users working with pipelines and functions.

1. Simple Output to Console

This is the most basic way to use Write-Output. It simply prints a string to the console.

Write-Output "Hello, world!"

While you can achieve the same result with just "Hello, world!", using Write-Output makes your intention clear, especially when writing more complex scripts.

2. Sending Objects Down the Pipeline

One powerful feature of PowerShell is the pipeline. You can pipe objects from one cmdlet to another. Write-Output helps you inject custom output into this flow.

Write-Output 1,2,3,4,5 | ForEach-Object { $_ * 2 }

This sends the numbers 1 to 5 down the pipeline, where each is multiplied by 2. The output will be: 2, 4, 6, 8, 10.

3. Returning Values from Functions

When creating your own functions, using Write-Output ensures that your function emits output to the pipeline correctly.

function Get-Greeting {
    param (
        [string]$Name
    )
    Write-Output "Hello, $Name!"
}

Get-Greeting -Name "PowerShell User"

The above function returns a friendly greeting, using Write-Output.

4. Conditional Output for Logging

In more advanced scripts, you might want to emit output only if a flag is set, such as when enabling verbose or debug logging.

param(
    [string]$Path = ".",
    [switch]$VerboseMode
)

$files = Get-ChildItem -Path $Path

if ($VerboseMode) {
    Write-Output "Found $($files.Count) files in $Path"
}

$files | Where-Object { $_.Length -gt 1MB }

Here, Write-Output conditionally logs how many files were found, depending on a -VerboseMode flag. This is great for maintaining clean script output while still having logging available when needed.

Wrap-Up

Write-Output is a foundational part of any PowerShell scripter’s toolkit. It’s simple to use, yet powerful in the way it integrates with PowerShell’s object-based pipeline. From simple console messages to advanced script logging and function output management, Write-Output delivers consistently.

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 *