0
0
PowerShellscripting~5 mins

Automatic variables ($_, $PSVersionTable) in PowerShell

Choose your learning style9 modes available
Introduction

Automatic variables in PowerShell hold special information that helps scripts run smoothly without extra setup.

When processing items in a list or pipeline and you want to refer to the current item easily.
When you need to check the version of PowerShell running your script.
When writing quick scripts that handle data flowing through commands without naming variables.
When debugging or logging to see environment details like PowerShell version.
Syntax
PowerShell
$_
$PSVersionTable

$_ represents the current object in the pipeline.

$PSVersionTable is a read-only table showing PowerShell version details.

Examples
This filters processes using more than 100 CPU units, using $_ to refer to each process.
PowerShell
Get-Process | Where-Object { $_.CPU -gt 100 }
This prints the PowerShell version number.
PowerShell
Write-Output $PSVersionTable.PSVersion
Prints the name of each service using $_ inside a loop.
PowerShell
Get-Service | ForEach-Object { "Service: $_.Name" }
Sample Program

This script first shows PowerShell version info, then lists all running services by using $PSVersionTable and $_.

PowerShell
Write-Output "PowerShell version info:"
Write-Output $PSVersionTable

"List of running services with status:" | Write-Output
Get-Service | Where-Object { $_.Status -eq 'Running' } | ForEach-Object { Write-Output "Service: $_.Name" }
OutputSuccess
Important Notes

$_ only works inside commands that process pipeline input like ForEach-Object or Where-Object.

$PSVersionTable is useful to check compatibility before running scripts.

Summary

$_ is the current item in a pipeline, making it easy to work with each piece of data.

$PSVersionTable shows details about your PowerShell version and environment.

These automatic variables help write shorter, clearer scripts without extra setup.