Powershell

What are Automatic Variables in PowerShell

PowerShell’s “Automatic Variables” are essential for system management, automation, and scripting activities. These variables are built-in by the PowerShell runtime and serve as placeholders to store and reference specific information during the execution of a script or command. Understanding and utilizing these automatic variables effectively can greatly enhance the efficiency and functionality of PowerShell scripts.

This article aims to explore the concept of “Automatic Variables” in PowerShell, their significance, and how they can be leveraged in various scenarios.

What are Automatic Variables in PowerShell?

To begin, let’s delve into the definition of “Automatic Variables”. These variables are predefined and are created automatically by PowerShell during script execution. These serve different purposes, including providing information about the system, command-line arguments, script-related details, and much more.

PowerShell offers several “Automatic Variables” and each of them serves a distinct purpose in script execution. These variables are, as follows:

1. $PSVersionTable

One of the fundamental automatic variables in PowerShell is “$PSVersionTable”. This variable allows script developers to ascertain the version of PowerShell being utilized, which can be crucial when considering the compatibility and availability of certain features and functionalities.

The following properties are associated with this variable:

PSVersion: Returns the PowerShell version number.

PSEdition: For PowerShell 4 and earlier, as well as PowerShell 5.1 on full-featured Windows versions, this property has the value “Desktop.” This characteristic has the value of Core for PowerShell 6 and later, as well as Windows PowerShell 5.1 for low-footprint editions like Windows Nano Server or Windows IoT.

GitCommitId: Fetches the source files’ GitHub commit ID.

OS: Logs information about the computer system that PowerShell is using.

Platform: Returns the operating system’s supporting platform. Unix has value on Linux and macOS. Check out $IsMacOs and $IsLinux.

PSCompatibleVersions: PowerShell versions that are compatible with the current version are returned.

PSRemotingProtocolVersion: Returns the version number for the PowerShell remote management protocol.

SerializationVersion: Returns the serialization method’s version.

WSManStackVersion: Returns the WS-Management stack’s version number.

$PSVersionTable

 

2. $Args

Another essential automatic variable in PowerShell is “$Args”, which contains an array of command-line arguments passed to a script or function. This variable empowers developers to process and manipulate the provided arguments dynamically within their scripts.

When defining a function, you may either use the “param” keyword to declare the parameters or you can add a comma-separated list of parameters in parentheses following the function name. An event action’s “$Args” variable stores objects that serve as placeholders for the event parameters of the event being handled:

foreach ($arg in $Args) {
    Write-Host $arg
}

 

3. $MyInvocation

The “$MyInvocation” variable gives crucial background data about the script or procedure that is presently running. It offers properties such as the script name, script line number, and whether the script is being run interactively or non-interactively. These properties help script developers implement branching logic, define error-handling mechanisms, or generate meaningful logging and reporting:

$MyInvocation

 

4. $Error

A lesser-known automatic variable “$Error”, effectively captures any error messages or exceptions that occur during script execution. “$Error” can be accessed to retrieve specific error details such as exception messages, stack traces, or error codes, enabling detailed analysis and debugging.

The most recent error is represented by the first error object in the array “$Error[0]“. You can use the ErrorAction common option with the value “Ignore” to stop the errors from being added to the “$Error” array.

Suppose we typed an accurate command:

ip[onfig

 

Now, if we enter the “$Error” cmdlet:

$Error

 

5. $PSCmdlet

When working with PowerShell modules, the automatic variable “$PSCmdlet” comes into effect. This variable provides access to the current instance of the cmdlet or function being invoked, facilitating direct interaction with its properties and methods.

Using “$PSCmdlet”, advanced script developers can fine-tune and enhance the behavior of modules by extending or modifying the built-in functionalities. You can use the object’s attributes and methods in your cmdlet or function code in response to the criteria of use:

function typeof-psCmdlet {
  [cmdletBinding()] param()
   echo "type of `$psCmdlet is $($psCmdlet.GetType().FullName)"
}

typeof-psCmdlet

 

In addition to the aforementioned variables, PowerShell encompasses automatic variables like $HOME, $PROFILE, $PWD, and many more, which serve different purposes, such as accessing input, tracking errors, retrieving environment information, managing parameters, and much more. These variables are listed below:

Automatic Variables Description
$$ Holds the last token in the previous line received by the PowerShell session.
$? Stores the execution status of the last command.
$^ Contains the first token of the last line received by the session.
$_ Represents the current object in the pipeline.
$ConsoleFileName Contains the path of the console file (.psc1) most recently used in the session.
$EnabledExperimentalFeatures Contains a list of the enabled experimental features.
$Event Contains a “PSEventArgs” object representing the event being processed.
$EventArgs Contains the first event argument of the event being processed.
$EventSubscriber Represents the event subscriber of the event being processed.
$ExecutionContext Represents the execution context of the PowerShell host.
$false Represents the Boolean value “False”.
$foreach Contains the enumerator of a “for-Each” loop.
$HOME Contains the full path of the user’s home directory.
$Host Represents the current host application for PowerShell.
$input Serves as an enumerator for all input passed to a function or script.
$IsCoreCLR Indicates if the session is running on the .NET Core Runtime (CoreCLR).
$IsLinux Indicates if the session is running on a Linux operating system.
$IsMacOS Indicates if the session is running on a MacOS operating system.
$IsWindows Identifies if the session is running on a Windows operating system.
$LASTEXITCODE Stores the exit code of the last native program or PowerShell script.
$Matches Contains matched strings from the “-match” and “-notmatch” operators.
$NestedPromptLevel Tracks the current prompt level in nested commands or debugging scenarios.
$null Represents a null or empty value.
$PID Contains the process identifier (PID) of the PowerShell session.
$PROFILE Contains the full path of the PowerShell profile for the current user and host application.
$PSBoundParameters Holds a dictionary of parameters passed to a script or function and their values.
$PSCommandPath Contains the full path and filename of the script being executed.
$PSCulture Reflects the culture of the current PowerShell run space.
$PSEdition Contains the PowerShell edition information.
$PSHOME Contains the full path of the PowerShell installation directory.
$PSItem Same as $_, represents the current object in the pipeline.
$PSScriptRoot Contains the full path of the executing script’s parent directory.
$PSSenderInfo Contains information about the user who started the PSSession.
$PSUICulture Reflects the user interface (UI) culture configured in the operating system.
$PWD Represents the current working directory of the PowerShell session.
$Sender Contains the object that generated an event.
$ShellId Contains the identifier of the current shell.
$StackTrace Stores the stack trace for the most recent error.
$switch Contains the enumerator of the “Switch” statement.
$this Refers to the instance of a class in script blocks that extend classes.
$true Represents the Boolean value “True”.

 

All the “automatic variables” in PowerShell can be found by running the below command:

Get-Variable

 

Conclusion

Automatic Variables” form the backbone of PowerShell scripting, allowing developers to obtain information about the system, command-line arguments, script execution context, and more. By harnessing automatic variables such as “$PSVersionTable”, “$Args”, “$MyInvocation”, “$Error”, and others, PowerShell script developers can create streamlined system administration practices.

About the author

Hiba Shafqat

I am a Computer Science student and a committed technical writer by choice. It is a great pleasure to share my knowledge with the world in which I have academic expertise.