PowerShell Pipeline Variables [With Examples]

Recently, I gave an online session on pipeline variables for a PowerShell user group. In this tutorial, I will explain everything about PowerShell pipeline variables with examples.

Pipeline variables in PowerShell, introduced with the -PipelineVariable parameter in PowerShell 7, allow you to store the output of a command within a pipeline for reuse later in the same pipeline. For example, using Get-Process | ForEach-Object -PipelineVariable proc { Write-Output "Process Name: $($proc.Name)" }, you can assign each process object to the variable $proc and access its properties multiple times within the ForEach-Object block.

What is a Pipeline Variable in PowerShell?

A pipeline variable in PowerShell is a special type of variable used to store the output of a command in a pipeline for further use down the line. This feature is particularly useful when you want to manipulate or refer to the output of a command multiple times within the same pipeline.

The -PipelineVariable Parameter

Introduced in PowerShell 7, the -PipelineVariable parameter allows you to assign the output of a command to a variable that can be accessed later in the pipeline. This parameter can be a game-changer for complex scripts where maintaining readability and efficiency is crucial.

Basic Usage of the PowerShell Pipeline Variables

Let’s start with a simple example to understand the basic usage of the -PipelineVariable parameter in PowerShell:

Get-Process -PipelineVariable proc | ForEach-Object {
    Write-Output "Process Name: $($proc.Name)"
    Write-Output "Process ID: $($proc.Id)"
}

In this example, the Get-Process cmdlet retrieves a list of processes running on the system. The ForEach-Object cmdlet processes each object in the pipeline and assigns it to the variable $proc using the -PipelineVariable parameter. We then use $proc to output the process name and ID.

Here is the output in the screenshot below:

PowerShell Pipeline Variables

Check out PowerShell String Replace

PowerShell Pipeline Variables: Examples

Now, let me show you a few examples of how to use pipeline variables in PowerShell.

Example 1: Get File Information

Here is an example of using pipeline variables in PowerShell.

Here is the complete PowerShell script.

Get-ChildItem -Path C:\MyFolder -Recurse -File -PipelineVariable files |
    Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) } |
    Select-Object Name, LastWriteTime, @{Name='SizeMB';Expression={$files.Length / 1MB}}

In this example, we’re using -PipelineVariable files to store the results of Get-ChildItem. This allows us to access the full file information later in the pipeline, even after filtering with Where-Object.

Here is the output in the screenshot below:

Pipeline Variables in PowerShell

Check out How to Set and Get Environment Variables in PowerShell?

Example 2: Disk Space Monitoring

Here is another example.

Monitoring disk space is a common administrative task. Let’s create a script that checks the available disk space on multiple servers and sends an alert if the free space is below a certain threshold:

$servers = "Server1", "Server2", "Server3"
$threshold = 20GB

$servers | ForEach-Object -PipelineVariable server {
    Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName $server | ForEach-Object -PipelineVariable disk {
        if ($disk.FreeSpace -lt $threshold) {
            Write-Output "Alert: $($disk.DeviceID) on $server has less than 20GB free space."
        } else {
            Write-Output "$($disk.DeviceID) on $server has sufficient free space."
        }
    }
}

This script retrieves disk information from each server and checks if the free space is below the specified threshold. If it is, an alert message is generated.

Example 3: User Account Management

Suppose you need to manage user accounts in Active Directory. You want to find all users in a specific organizational unit (OU) and disable their accounts if they haven’t logged in for the past 90 days:

$ou = "OU=Sales,DC=example,DC=com"
$daysInactive = 90
$cutoffDate = (Get-Date).AddDays(-$daysInactive)

Get-ADUser -Filter * -SearchBase $ou -Properties LastLogonDate | ForEach-Object -PipelineVariable user {
    if ($user.LastLogonDate -lt $cutoffDate) {
        Disable-ADAccount -Identity $user
        Write-Output "Disabled account for $($user.SamAccountName)"
    } else {
        Write-Output "Account for $($user.SamAccountName) is active."
    }
}

In this example, we search for all users in the specified OU and check their last logon date. If a user hasn’t logged in for the past 90 days, their account is disabled, and a message is output indicating the action taken.

Conclusion

Pipeline variables in PowerShell is useful to manage and manipulate data within a pipeline. By using the -PipelineVariable parameter, you can create more readable and efficient scripts while working with complex tasks. In this tutorial, I will show you how use pipeline variables in PowerShell.

You may also like the following tutorials:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.