PowerShell Predefined Variables

By Xah Lee. Date: 2009-07-30. Last updated: 2012-03-31.

PowerShell has several predefined variables, called automatic variables. Some of them are used for scripting, some give info about the environment.
For example, $_ is a variable that contains the current argument (similar to Perl's “$_”), and is a most frequently used variable in scripting. The $Host is a variable that contains info about current PowerShell environment.

This page gives explanation and sample use, of the most frequently used automatic variables. The page is divided into 2 sections. One section on environment related variables, and the other section is about scripting related variables.

For a complete list of automatic variables, type help about_automatic_variable.

Scripting Related Automatic Variables

Standard Values

$True

If you simply type “true” in the command line, it's a error, because PowerShell tries to interprete it as a command or expression. By design, “true” or “false” are not recognized as expressions.

PowerShell True/False Interpretation

Value

Value in Boolean Context

$true

True

Nonzero number

True

Nonempty string

True

Nonempty array

True

Hashtable (empty or not)

True

$false

False

$null

False

Zero

False

Empty string

False

Empty array

False

$False

Evaluates to the .NET “False”.

$NULL

Eval to the .NET “Null”.

Arguments and Script Name

$_

The current object in a pipeline.

Note that a pipe can pass multiple objects, and each one is processed in turn. The “$_” is the current one.

Example use:

# get all aliases of get-childitem
get-alias | where-object {$_.Definition-eq"get-childitem"}

In the above, the “get-alias” returns many objects.
We use the syntax “xyz.Definition” to refer to the “Definition” property of the object xyz. In this case, we use “$_” to refer to the current object, instead of a object name such as “xyz”.

$Args

A array of the argument received by your function or script or block of code.

Note, PowerShell provide a few ways to define how a function receives its arguments. A function can be defined with explicit parameters, or it can be defined without explicit parameters. When a function does not have explicit parameters, it can still receive arguments, and these arguments can be accessed by $Args.