PowerShell


Automatic Variables All Versions

1.0
2.0
3.0
4.0
5.0
5.1 Preview

This draft deletes the entire topic.

Introduction

Automatic Variables are created and maintained by Windows PowerShell. One has the ability to call a variable just about any name in the book; The only exceptions to this are the variables that are already being managed by PowerShell. These variables, without a doubt, will be the most repetitious objects you use in PowerShell next to functions (like $? - indicates Success/ Failure status of the last operation)

expand all collapse all

Examples

  • 4

    Contains status of the last operation. When there is no error, it is set to True:

    PS C:\> Write-Host "Hello"
    Hello
    PS C:\> $?
    True
    

    If there is some error, it is set to False:

    PS C:\> wrt-host
    wrt-host : The term 'wrt-host' is not recognized as the name of a cmdlet, function, script file, or operable program.
    Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:1
    + wrt-host
    + ~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (wrt-host:String) [], CommandNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException
    
    PS C:\> $?
    False
    
  • 4

    Variable called Output Field Separator contains string value that is used when converting an array to a string. By default $OFS = " " (a space), but it can be changed:

    PS C:\> $array = 1,2,3
    PS C:\> "$array" # default OFS will be used
    1 2 3
    PS C:\> $OFS = ",." # we change OFS to comma and dot
    PS C:\> "$array"
    1,.2,.    3
    
  • 3

    $null is used to represent absent or undefined value.
    $null can be used as an empty placeholder for empty value in arrays:

    PS C:\> $array = 1, "string", $null
    PS C:\> $array.Count
    3
    

    When we use the same array as the source for ForEach-Object, it will process all three items (including $null):

    PS C:\> $array | ForEach-Object {"Hello"}
    Hello
    Hello
    Hello
    

    Be careful! This means that ForEach-Object WILL process even $null all by itself:

    PS C:\> $null | ForEach-Object {"Hello"} # THIS WILL DO ONE ITERATION !!!
    Hello
    

    Which is very unexpected result if you compare it to classic foreach loop:

    PS C:\> foreach($i in $null) {"Hello"} # THIS WILL DO NO ITERATION
    PS C:\>
    
Please consider making a request to improve this example.

Syntax

Syntax

Parameters

Parameters

Remarks

Remarks

Still have a question about Automatic Variables? Ask Question

Topic Outline