• Skip to primary navigation
  • Skip to main content
  • Skip to footer

Stephanos Constantinou Blog

PowerShell Scripting

  • Home
  • Blogs
    • PowerShell Tutorials
    • PowerShell Scripts
    • PowerShell Modules
      • Modules Cmdlets
    • Software Reviews
  • About
  • Contact
You are here: Home / PowerShell Tutorials / PowerShell Automatic Variables

PowerShell Automatic Variables

08/08/2018 by Stephanos Leave a Comment

PowerShell Automatic Variables

In this tutorial we will see about PowerShell Automatic Variables. As Microsoft describes, these variables store state information for PowerShell. They are created automatically and maintained by PowerShell. Ideally, PowerShell Automatic Variables are considered to be read-only. Although you are able to write to them, you should avoid writing to those variables in order to keep backward compatibility.

Below I will provide the list of those PowerShell Automatic Variables. Then we go through each one of them to see what it does and some examples. I will provide the direct description from Microsoft in order to provide you with the exact information about them. I will provide you with some examples for them in order to understand better the information that can provide you.

This tutorial can be used mostly for reference guide of PowerShell Automatic Variables. Unfortunately the list is long and so this tutorial. I tried to help you out with jumps to specific sections  that you are more interested.

[adinserter name=”In Article”]

 

PowerShell Automatic Variables List:

  • $$ – Go to…
  • $? – Go to…
  • $^ – Go to…
  • $_ – Go to…
  • $Args – Go to…
  • $ConsoleFileName – Go to…
  • $Error – Go to…
  • $Event – Go to…
  • $EventArgs – Go to…
  • $EventSubscriber – Go to…
  • $ExecutionContext – Go to…
  • $False – Go to…
  • $ForEach – Go to…
  • $Home – Go to…
  • $Host – Go to…
  • $Input – Go to…
  • $LastExitCode – Go to…
  • $Matches – Go to…
  • $MyInvocation – Go to…
  • $NestedPromptLevel – Go to…
  • $Null – Go to…
  • $PID – Go to…
  • $Profile – Go to…
  • $PSBoundParameters – Go to…
  • $PSCmdLet – Go to…
  • $PSCommandPath – Go to…
  • $PSCulture – Go to…
  • $PSDebugContext – Go to…
  • $PSHome – Go to…
  • $PSItem – Go to…
  • $PSScriptRoot – Go to…
  • $PSSenderInfo – Go to…
  • $PSUICulture – Go to…
  • $PSVersionTable – Go to…
  • $PWD – Go to…
  • $Sender – Go to…
  • $ShellID – Go to…
  • $StackTrace – Go to…
  • $This – Go to…
  • $True  – Go to…


 [adinserter name=”In Article”]

 

$$

Microsoft’s description:

Contains the last token in the last line received by the session.

Example 1

PowerShell Automatic Variables - Example 1

Back to List

[adinserter name=”In Article”]

 

$?

Microsoft’s description:

Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.

Example 2

PowerShell Automatic Variables - Example 2

Back to List

[adinserter name=”In Article”]

 

$^

Microsoft’s description:

Contains the first token in the last line received by the session.

Example 3

PowerShell Automatic Variables - Example 3

Back to List

[adinserter name=”In Article”]

 

$_

Microsoft’s description:

Same as $PSItem. Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

Example 4

PowerShell Automatic Variables - Example 4

Back to List

 [adinserter name=”In Article”]

 

$Args

Microsoft’s description:

Contains an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block. When you create a function, you can declare the parameters by using the param keyword or by adding a comma-separated list of parameters in parentheses after the function name.

In an event action, the $Args  variable contains objects that represent the event arguments of the event that is being processed. This variable is populated only within the Action block of an event registration command. The value of this variable can also be found in the SourceArgs property of the PSEventArgs object (System.Management.Automation.PSEventArgs) that Get-Event returns.

Example 5

Code:

$a = 1
$b = 2
$c = 3
$d = 4
$e = 5
$f = '$Args are working fine'

function Test-Args () {
    foreach ($_ in $args){
        Write-Host $_
    }
}
Test-Args $a $b $c $d $e $f

 

Output:

PowerShell Automatic Variables - Example 5

Back to List

 [adinserter name=”In Article”]

 

$ConsoleFileName

Microsoft’s description:

Contains the path of the console file (.psc1) that was most recently used in the session. This variable is populated when you start PowerShell with the PSConsoleFile parameter or when you use the Export-Console cmdlet to export snap-in names to a console file.

When you use the Export-Console cmdlet without parameters, it automatically updates the console file that was most recently used in the session. You can use this automatic variable to determine which file will be updated.

Example 6

Code:

Export-Console -Path C:\Scripts_Output\TestingConsole.psc1

 

Output:

PowerShell Automatic Variables - Example 6

Back to List

 [adinserter name=”In Article”]

 

$Error

Microsoft’s description:

Contains an array of error objects that represent the most recent errors. The most recent error is the first error object in the array ($Error[0]).

Example 7

PowerShell Automatic Variables - Example 7

Back to List

 [adinserter name=”In Article”]

 

$Event

Microsoft’s description:

Contains a PSEventArgs object that represents the event that is being processed. This variable is populated only within the Action block of an event registration command, such as Register-ObjectEvent. The value of this variable is the same object that the Get-Event cmdlet returns. Therefore, you can use the properties of the $Event variable, such as $Event.TimeGenerated , in an Action script block.

Back to List

 

$EventArgs

Microsoft’s description:

Contains an object that represents the first event argument that derives from EventArgs of the event that is being processed. This variable is populated only within the Action block of an event registration command. The value of this variable can also be found in the SourceEventArgs property of the PSEventArgs (System.Management.Automation.PSEventArgs) object that Get-Event returns.

Back to List

 [adinserter name=”In Article”]

 

$EventSubscriber

Microsoft’s description:

Contains a PSEventSubscriber object that represents the event subscriber of the event that is being processed. This variable is populated only within the Action block of an event registration command. The value of this variable is the same object that the Get-EventSubscriber cmdlet returns.

Back to List

 

$ExecutionContext

Microsoft’s description:

Contains an EngineIntrinsics object that represents the execution context of the PowerShell host. You can use this variable to find the execution objects that are available to cmdlets.

Example 8

PowerShell Automatic Variables - Example 8

Back to List

 [adinserter name=”In Article”]

 

$False

Microsoft’s description:

Contains FALSE. You can use this variable to represent FALSE in commands and scripts instead of using the string “false”. The string can be interpreted as TRUE if it is converted to a non-empty string or to a non-zero integer.

Example 9

PowerShell Automatic Variables - Example 9

Back to List

 [adinserter name=”In Article”]

 

$ForEach

Microsoft’s description:

Contains the enumerator (not the resulting values) of a ForEach loop. You can use the properties and methods of enumerators on the value of the $ForEach variable. This variable exists only while the ForEach loop is running; it is deleted after the loop is completed. For detailed information, see about_ForEach.

Example 10

Code:

$array = @(1,2,3,4,5)
foreach ($_ in $array){
    Write-Host "Value is: $_"
    Write-Host "Enumerator is $foreach"
}

 

Output:

PowerShell Automatic Variables - Example 10

Back to List

[adinserter name=”In Article”]

 

$Home

Microsoft’s description:

Contains the full path of the user’s home directory. This variable is the equivalent of the %homedrive%%homepath% Windows environment variables, typically C:\Users\.

Example 11

PowerShell Automatic Variables - Example 11

Back to List

 [adinserter name=”In Article”]

 

$Host

Microsoft’s description:

Contains an object that represents the current host application for PowerShell. You can use this variable to represent the current host in commands or to display or change the properties of the host, such as $Host.version or $Host.CurrentCulture, or $host.ui.rawui.setbackgroundcolor(“Red”).

Example 12

PowerShell Automatic Variables - Example 12

Back to List

 [adinserter name=”In Article”]

 

$Input

Microsoft’s description:

Contains an enumerator that enumerates all input that is passed to a function. The $input variable is available only to functions and script blocks (which are unnamed functions). In the Process block of a function, the $input variable enumerates the object that is currently in the pipeline. When the Process block completes, there are no objects left in the pipeline, so the $input variable enumerates an empty collection. If the function does not have a Process block, then in the End block, the $input variable enumerates the collection of all input to the function.

Example 13

Code:

$array = @(1,2,3,4,5)
function test-input(){
    foreach ($_ in $input){
        Write-Host $_
    }
}
$array | test-input

 

Output:

PowerShell Automatic Variables - Example 13

Back to List

 [adinserter name=”In Article”]

 

$LastExitCode

Microsoft’s description:

Contains the exit code of the last Windows-based program that was run.

Example 14

PowerShell Automatic Variables - Example 14

Back to List

 [adinserter name=”In Article”]

 

$Matches

Microsoft’s description:

The $Matches variable works with the -match and -notmatch operators. When you submit scalar input to the -match or -notmatch operator, and either one detects a match, they return a Boolean value and populate the $Matches automatic variable with a hash table of any string values that were matched. For more information about the -match operator, see about_comparison_operators.

Example 15

PowerShell Automatic Variables - Example 15

Back to List

[adinserter name=”In Article”] 

 

$MyInvocation

Microsoft’s description:

Contains an information about the current command, such as the name, parameters, parameter values, and information about how the command was started, called, or “invoked,” such as the name of the script that called the current command.

$MyInvocation is populated only for scripts, function, and script blocks. You can use the information in the System.Management.Automation.InvocationInfo object that $MyInvocation returns in the current script, such as the path and file name of the script ($MyInvocation.MyCommand.Path) or the name of a function ($MyInvocation.MyCommand.Name) to identify the current command. This is particularly useful for finding the name of the current script.

Beginning in PowerShell 3.0, $MyInvocation has the following new properties.

  • PSScriptRoot – Contains the full path to the script that invoked the current command. The value of this property is populated only when the caller is a script.
  • PSCommandPath – Contains the full path and file name of the script that invoked the current command. The value of this property is populated only when the caller is a script.

Unlike the $PSScriptRoot and $PSCommandPath automatic variables, the PSScriptRoot and PSCommandPath properties of the $MyInvocation automatic variable contain information about the invoker or calling script, not the current script.

Example 16

PowerShell Automatic Variables - Example 16

Back to List

 [adinserter name=”In Article”]

 

$NestedPromptLevel

Microsoft’s description:

Contains the current prompt level. A value of 0 indicates the original prompt level. The value is incremented when you enter a nested level and decremented when you exit it.

For example, PowerShell presents a nested command prompt when you use the $Host.EnterNestedPrompt method. PowerShell also presents a nested command prompt when you reach a breakpoint in the PowerShell debugger.

When you enter a nested prompt, PowerShell pauses the current command, saves the execution context, and increments the value of the $NestedPromptLevel variable. To create additional nested command prompts (up to 128 levels) or to return to the original command prompt, complete the command, or type “exit”.

The $NestedPromptLevel variable helps you track the prompt level. You can create an alternative PowerShell command prompt that includes this value so that it is always visible.

Back to List

 

$Null

Microsoft’s description:

$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

Example 17

There are some people that think $null value is the same. Based on the description above it is not the same check the below screen shot.

PowerShell Automatic Variables - Example 17

Back to List

 [adinserter name=”In Article”]

 

$PID

Microsoft’s description:

Contains the process identifier (PID) of the process that is hosting the current PowerShell session.

Example 18

PowerShell Automatic Variables - Example 18

Back to List

 

$Profile

Microsoft’s description:

Contains the full path of the PowerShell profile for the current user and the current host application. You can use this variable to represent the profile in commands. For example, you can use it in a command to determine whether a profile has been created:

Example 19

PowerShell Automatic Variables - Example 19

Back to List

 [adinserter name=”In Article”]

 

$PSBoundParameters

Microsoft’s description:

Contains a dictionary of the parameters that are passed to a script or function and their current values. This variable has a value only in a scope where parameters are declared, such as a script or function. You can use it to display or change the current values of parameters or to pass parameter values to another script or function.

Example 20

Code:

function Get-Parameters () {
    param(
        [string]$FirstWord,
        [string]$SecondWord
    )
    
    foreach ($_ in $PSBoundParameters.GetEnumerator()){
        Write-Host $_}
}
Get-Parameters "Hello" "World"

 

Output:

PowerShell Automatic Variables - Example 20

Back to List

 [adinserter name=”In Article”]

 

$PSCmdLet

Microsoft’s description:

Contains an object that represents the cmdlet or advanced function that is being run.

You can use the properties and methods of the object in your cmdlet or function code to respond to the conditions of use. For example, the ParameterSetName property contains the name of the parameter set that is being used, and the ShouldProcess method adds the WhatIf and Confirm parameters to the cmdlet dynamically.

Back to List

 

$PSCommandPath

Microsoft’s description:

Contains the full path and file name of the script that is being run. This variable is valid in all scripts.

Back to List

 

$PSCulture

Microsoft’s description:

Contains the name of the culture currently in use in the operating system. The culture determines the display format of items such as numbers, currency, and dates. This is the value of the System.Globalization.CultureInfo.CurrentCulture.Name property of the system. To get the System.Globalization.CultureInfo object for the system, use the Get-Culture cmdlet.

Example 21

PowerShell Automatic Variables - Example 21

Back to List

 [adinserter name=”In Article”]

 

$PSDebugContext

Microsoft’s description:

While debugging, this variable contains information about the debugging environment. Otherwise, it contains a NULL value. As a result, you can use it to indicate whether the debugger has control. When populated, it contains a PsDebugContext object that has Breakpoints and InvocationInfo properties. The InvocationInfo property has several useful properties, including the Location property. The Location property indicates the path of the script that is being debugged.

Example 22

PowerShell Automatic Variables - Example 22

Back to List

 

$PSHome

Microsoft’s description:

Contains the full path of the installation directory for PowerShell, typically, %windir%\System32\PowerShell\v1.0 in Windows systems. You can use this variable in the paths of PowerShell files. For example, the following command searches the conceptual Help topics for the word “variable”:

Example 23

PowerShell Automatic Variables - Example 23

Back to List

 [adinserter name=”In Article”]

 

$PSItem

Microsoft’s description:

Same as $_. Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

Example 24

PowerShell Automatic Variables - Example 24

Back to List

 

$PSScriptRoot

Microsoft’s description:

Contains the directory from which a script is being run.

In PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in PowerShell 3.0, it is valid in all scripts.

Back to List

 [adinserter name=”In Article”]

 

$PSSenderInfo

Microsoft’s description:

Contains information about the user who started the PSSession, including the user identity and the time zone of the originating computer. This variable is available only in PSSessions.

The $PSSenderInfo variable includes a user-configurable property, ApplicationArguments, which, by default, contains only the $PSVersionTable from the originating session. To add data to the ApplicationArguments property, use the ApplicationArguments parameter of the New-PSSessionOption cmdlet.

Back to List

 

$PSUICulture

Microsoft’s description:

Contains the name of the user interface (UI) culture that is currently in use in the operating system. The UI culture determines which text strings are used for user interface elements, such as menus and messages. This is the value of the System.Globalization.CultureInfo.CurrentUICulture.Name property of the system. To get the System.Globalization.CultureInfo object for the system, use the Get-UICulture cmdlet.

Example 25

PowerShell Automatic Variables - Example 25

Back to List

 [adinserter name=”In Article”]

 

$PSVersionTable

Microsoft’s description:

Contains a read-only hash table that displays details about the version of PowerShell that is running in the current session. 

  • BuildVersion – The build number of the current version
  • CLRVersion – The version of the common language runtime (CLR)
  • GitCommitId – The commit Id of the source files, in GitHub, used in this version of PowerShell
  • PSCompatibleVersions – Versions of PowerShell that are compatible with the current version
  • PSEdition – This property has the value of ‘Desktop’, for Windows Server and Windows client versions. This property has the value of ‘Core’ for PowerShell running under Nano Server or Windows IOT.
  • PSRemotingProtocolVersion – The version of the PowerShell remote management protocol.
  • PSVersion – The PowerShell version number
  • SerializationVersion – The version of the serialization method
  • WSManStackVersion – The version number of the WS-Management stack

Example 26

PowerShell Automatic Variables - Example 26

Back to List

 

$PWD

Microsoft’s description:

Contains a path object that represents the full path of the current directory.

Example 27

PowerShell Automatic Variables - Example 27

Back to List

 [adinserter name=”In Article”]

 

$Sender

Microsoft’s description:

Contains the object that generated this event. This variable is populated only within the Action block of an event registration command. The value of this variable can also be found in the Sender property of the PSEventArgs (System.Management.Automation.PSEventArgs) object that Get-Event returns.

Back to List

 

$ShellID

Microsoft’s description:

Contains the identifier of the current shell.

Example 28

PowerShell Automatic Variables - Example 28

Back to List

 

$StackTrace

Microsoft’s description:

Contains a stack trace for the most recent error.

Back to List

 [adinserter name=”In Article”]

 

$This

Microsoft’s description:

In a script block that defines a script property or script method, the $This variable refers to the object that is being extended.

Example 29

Code:

$a = @{Key = "Hello"; Value = "World"}
$Object = New-Object -TypeName psobject -Property $a
Add-Member -Name list -InputObject $Object -MemberType ScriptMethod -Value {$this}
$Object.list()

 

Output:

PowerShell Automatic Variables - Example 29

Back to List

 

$True

Microsoft’s description:

Contains TRUE. You can use this variable to represent TRUE in commands and scripts.

Example 30

PowerShell Automatic Variables - Example 30

 

ReportErrorShow Variables

As Microsoft mentions there are some more automatic variables but they are for future use. The “ReportErrorShow” variables are defined in PowerShell, but they are not implemented. Get-Variable gets them, but they do not contain valid data.

  • $ReportErrorShowExceptionClass
  • $ReportErrorShowInnerException
  • $ReportErrorShowSource
  • $ReportErrotShowStackTrace

I hope the tutorial about PowerShell Automatic Variables is helpful.

Please let me know your comments and thoughts.

You feedback is appreciated.

[adinserter name=”In Article”]

Related Links:

  • PowerShell Tutorials
  • PowerShell Scripts
  • About Automatic Variables – Microsoft Docs
  • PowerShell Comparison Operators
  • Get-Date – Microsoft Docs
  • Get-NetAdapter – Microsoft Docs
  • Where-Object – Microsoft Docs
  • Get-Event – Microsoft Docs
  • Register-ObjectEvent – Microsoft Docs
  • Get-EventSubscriber – Microsoft Docs
  • Get-Variable – Microsoft Docs

[adinserter name=”Matched-Content”]

Summary
PowerShell Automatic Variables
Article Name
PowerShell Automatic Variables
Description
PowerShell Automatic Variables. In this tutorial you will find information about PowerShell Automatic Variables and their use. Stephanos Constantinou Blog
Author
Stephanos
Publisher Name
Stephanos Constantinou Blog
Publisher Logo
Stephanos Constantinou Blog

Filed Under: PowerShell Tutorials Tagged With: Comparison Operators, Get-Date, Get-Event, Get-EventSubscriber, Get-NetAdapter, Get-Variable, PowerShell ForEach, PowerShell Operators, Register-ObjectEvent, Where-Object

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Footer

Recent Posts

  • ICS Cube Product Review 26/04/2019
  • PowerShell Module SysInfo v1.2.0 15/03/2019
  • PowerShell Module SysInfo v1.1.2 13/11/2018
  • PowerShell Module SysInfo 24/10/2018
  • Get-VoltageProbe 24/10/2018
  • Get-VideoController 24/10/2018
  • Get-USBController 24/10/2018
  • Get-TrackPoint 24/10/2018
  • Get-TrackBall 24/10/2018
  • Get-TouchScreen 24/10/2018
Planet PowerShell

Categories

  • Modules Cmdlets (57)
  • PowerShell Modules (5)
  • PowerShell Scripts (38)
  • PowerShell Tutorials (35)
  • Software Reviews (2)

Archives

  • April 2019 (1)
  • March 2019 (1)
  • November 2018 (1)
  • October 2018 (56)
  • September 2018 (13)
  • August 2018 (9)
  • July 2018 (6)
  • June 2018 (8)
  • May 2018 (7)
  • April 2018 (9)
  • March 2018 (4)
  • February 2018 (6)
  • January 2018 (12)
  • December 2017 (4)
Top 10 PowerShell 2018

Blogroll

  • Planet PowerShell
  • Reddit – PowerShell
  • PowerShell Magazine
  • PowerShell.org
  • PowerShell Team Blog
  • Hey, Scripting Guy! Blog
  • Mike F Robbins
  • PowerShell Explained with Kevin Marquette
  • Mike Kanakos – Network Admin
  • The Lonely Administrator
  • AskME4Tech
PowerShell Blogs Sysadmin Blogs Banners for Top 20 Programming Blogs

© 2023 · Stephanos Constantinou Blog

  • Home
  • Blogs
  • About
  • Contact