Lessons In PowerShell - Variables and Declarations

   Submit to Reddit      

The following useful information is primarily taken from the Windows PowerShell Language Quick Reference (QuadFold.rtf) documentation.

Automatic Variables

PowerShell includes the following in-built variables:


Variable Declaration

Variables and other data elements may be instantiated in different scopes:

  • Variables in the global scope are visible in all scopes.
  • Variables in the script scope are visible to all scopes within that script file.
  • Variables in the local scope are visible only in the current scope and its children.
  • Private scope variables are visible only to that current scope.

A scope is created in the body of a shell function.


$[scope:]name or ${anyname} or ${any path}


$a = 1
$global:a = 1    # Visible everywhere
$local:a = 1    # defined in this scope and visible to children
$private:a=1    # same as local but invisible to child scopes
$script:a=1    # visible to everything in this script
$env:path = "d:\windows"
${C:\TEMP\testfile.txt}="This writes to a file"
Get-Variable -scope 1 a    #Gets value from the parent scope
Get-Variable -scope 2 a    # grandparent

Type Declaration

Variables also can be declared as specific data type by prefixing the variable declaration with the data type.

[bool] or [boolean]

A variable's type also can be declared as a .NET Framework class by using the full class name. For example:

[System.Int32] $amount = 1234

comments powered by Disqus