This page looks best with JavaScript enabled

Powershell Special Characters And Tokens

 ·   ·  ☕ 11 min read

This article originally started when I was actively involved in PowerShell development.
Now I am mostly updating it on request of my blog readers (people like you).

Are you looking for a character combination not listed here? Found a mistake? Let me know at neolisk@gmail.com.

$ (dollar sign)

Declare/use a variable. Powershell has a number of built-in variables (thanks to Rein), such as $null, $true or $false. These are case insensitive and usually read-only, either explicitly (they will produce an error if you try to reassign them), or silently ignoring any updates.

Example.

1
$abc = "123"

$_ (dollar underscore)

‘THIS’ token. Typically refers to the item inside a foreach loop.

Task: Print all items in a collection.

Solution.

1
... | foreach { Write-Host $_ }

$$ (double dollar, two dollars)

Last token of last command. Does NOT refer to the whole command.

Example.

1
2
Write-Host "Hello, world!"
$$

Output.

Hello, world!
Hello, world!

$^ (dollar sign + caret)

Thanks to Richard for accidentally finding this one.
First token of last command. Does NOT refer to the whole command.
Example.

1
2
Write-Host "Hello, world!"
$^

Output.

Hello, world!
Write-Host

$? (dollar sign + question mark)

Many google searches were looking for this information, so I experimentally found what it does.

Returns True or False value indicating whether previous command ended with an error. For some reason it does not catch all errors, but most of the time it works.

Task 1: See if a powershell cmdlet exists in the system.

Code.

1
2
3
SomeCmdLet #does not exists
$?
$?

Output.

The term 'SomeCmdLet' 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:15
+     SomeCmdLet <<<<  #does not exists
    + CategoryInfo          : ObjectNotFound: (SomeCmdLet:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
False    #error occured - previous cmdlet (SomeCmdLet) was not found
True     #no errors returned by the previous command ($?)

Task 2: See if a WMI class exists in the system

Code.

1
2
3
4
#intentional error, win32_processor is the right one
gwmi win32_processo -ErrorAction SilentlyContinue
$?
$?

Output.

False
True

[type] (square bracket + type name + square bracket)

Credit goes to Michael for suggesting to add this.

Aside from type casting, it can be used to specify strongly typed variables, particularly useful with arrays.

Yes, Powershell is pretty good as inferring the type of variables based on the actual values, but just in case you want to limit script input.

Example 1.

1
2
3
$a = 1,2,3 #declare an array of object containing integer values
$a = $a + 'hello'; #adding a string value at the end of object array is perfectly fine
$a

Output 1.

1
2
3
hello

Example 2.

1
2
3
[int[]]$a = 1,2,3 #declare an array of integer
$a = $a + 'hello'; #triggers an error, cannot add string to an array of integer
$a

Output 2.

Cannot convert value "hello" to type "System.Int32". Error: "Input string was not in a correct format."
1
2
3

$() (dollar sign + round brackets)

Thanks to Kevin for a suggestion to add this one.

Sub-expression operator for double-quoted strings. Whatever is in the brackets should be evaluated first.

Example.

1
2
$name = "Kevin";
"Hello, $name, there are $($name.length) characters in your name"

Output.

Hello, Kevin, there are 5 characters in your name

It can be used with any expression, so this will also work:

1
"There are $(2+3) characters in your name"

${} (dollar sign + curly brackets)

Thanks to Remco for a hint about it.

Declare or use a variable with non-standard characters in it, a more generalized syntax to $variableName. It adds support for punctuation or non-English characters.

References: StackOverflow, Technet, ss64.com.

Example.

1
2
${,,,} = 5
${,,,}

Output.

5

| (pipeline)

Catch output of the command and pass it to another command.

Task: Get list of processes and select top 3 items.

Solution.

1
Get-Process | Select-Object -first 3

% (percentage)

  1. Shortcut to foreach.

    Task: Print all items in a collection.

    Solution.

    1
    
    ... | % { Write-Host $_ }
    
  2. Remainder of division, same as Mod in VB.

    Example:

    1
    
    5 % 2
    

. (single dot)

Credit goes to Marc for asking to add this one.

  1. Include external powershell file as part of your script (also known as dot sourcing). Any functions or variables will become available in the current scope.

    1
    2
    3
    4
    
    #line 1 of your script
    . ./script.ps1 #include from current directory
    #line 2
    #use function or variable from script.ps1
    
  2. Accessing a non-static member of the class, or to fully qualify a namespace, same as in C# or another object oriented language.

    1
    2
    
    $a = "Hello"; #a is now a .NET string
    $a.Substring(1) #prints "ello"
    

As a reminder, to access static members you should use double colon (this case is described further on this page):

1
[System.Console]::Beep();

.. (double dot)

Specify a range.

Task: Print numbers 1 through 5 without a foreach loop.

Code.

1
1..5

Output.

1
2
3
4
5

… (triple dot)

Asked by Ezra, I was very excited to find an answer, and decided to post it here for everyone.

A combination of operators: a range operator (..) combined with a fractional value prefix (.), when the leading zero is omitted, for example, .7 = 0.7.

Remember that either side of the range is rounded to the nearest integer.

Code 1.

1
1...3 # all integer values between 1 and 0.3

Output 1.

1
0

Code 2.

1
1...7 # all integer values between 1 and 0.7

Output 2.

1

:: (double-colon)

Thanks to Darrell for asking about this one.

Reference static member of a class. The class name must be enclosed in square brackets.

Task: Compare two strings.

Code.

1
2
# Indent 4 spaces to fix excerpt parsing code (jekyll issue)
[string]::Equals("a", "b")

Output.

False

+ (plus sign)

Thanks to Cody for pointing at this feature of Powershell.

Aside from its natural use, i.e. addition of two arguments, you can also use a plus sign to reference a public nested class.

For official reference, see here. Thanks to David Brabant for help in figuring this out.

Code.

1
2
# Indent 4 spaces to fix excerpt parsing code (jekyll issue)
[System.Net.WebRequestMethods+Ftp]::UploadFile

Output.

STOR

+= (plus equals)

Thanks to Brian G.

Increments value on the left by the amount on the right (and stores result). For strings it means concatenation.

Very well known to C# developers, so not strictly a Powershell feature.

In Powershell, however, this operator has a special use - you can add elements to arrays.

Mostly syntactic sugar, the array is still recreated behind the scenes, so just to save a few characters.

Code.

1
2
3
4
5
6
7
$b = 1         #initialize a variable
$b += 2        #add 2
$b             #output 3 (1 + 2)

$a = @(1,2,3)  #initialize array with 3 elements
$a += 4        #add element number 4
$a             #output 4 elements

Output.

3

1
2
3
4

-- (double minus)

The end-of-parameters token. Credit goes to Claus.

All arguments following it are to be passed in their actual form as though double quotes were placed around them. It allows passing the parameter name to the command as a plain string. Without the token you will get an error. This is similar to stop parsing token, but here each argument is processed separately.

Example 1. Using the token.

1
Write-Output -- -InputObject

Output 1.

1
-InputObject

Example 2. If the token is not used.

1
Write-Output -InputObject

Output 2 (error).

1
2
Write-Output : Missing an argument for parameter 'InputObject'. Specify a parameter of type
'System.Management.Automation.PSObject[]' and try again.

Example 3. Prove that each argument is parsed separately.

1
Write-Output -- -UserName -Password

Output 3.

1
2
-UserName
-Password

--% (double minus + percentage sign)

Stop-parsing token - thanks to Michael for suggesting to add it.

Available since Powershell v3.0 (links to blogs @ MSDN), it stops Powershell style of parsing and allows to feed commands with special characters, without them being treated as such.

Example 1 (using –% magic).

1
Write-Host --% %USERNAME%,this=$something{weird}

Output 1.

--% %USERNAME%,this=$something{weird}

Example 2 (same thing, not using –% magic).

1
Write-Host %USERNAME%,this=$something{weird}

Output 2.

%USERNAME% this= weird

! (exclamation mark)

Thanks to Leo for asking about this one.

Shortcut to -not.

Code.

1
2
$a = $null;
if(!$a) { Write-Host '$a is null' }

Output.

$a is null

? (question mark)

Output all items that conform with condition (shortcut to where). Shortcut to the following:

1
foreach { if (...) {return ... } }

Task: Print all odd numbers between 1 and 5 (inclusive):

Code.

1
1..5 | ? { $_ % 2 }

Output.

1
3
5

` (backtick) + special character or sequence

  1. Continue command on the next line.

    Code.

    1
    2
    
    Write-Host `
    "Hello, world!"
    

    Output.

    Hello, world!
    
  2. Include a special symbol into a string. Available options:

  • `$ - include a dollar symbol in your string. If you don’t escape it, Powershell will assume you are trying to embed a variable.
  • `0 - Null. My preference is using $null instead.
  • `a - Alert. Yes, it does make sound, and you can use multiple for multiple beeps.
  • `b - Backspace
  • `f - form feed - only affects printed documents.
  • `n - New line
  • `r - Carriage return
  • `t - Horizontal tab
  • `v - Vertical tab - only affects printed documents.
  • `u{x} - Unicode escape sequence (new in PowerShell 6). Suggested by Claus.
  • `' - Single quote - I prefer using double quotes when I need to escape a single one, since I don’t need any escaping in this case.
  • `" - Double quote - you can use single quotes, and you don’t need this symbol. My preference is use standard escaping instead, so 4 double quotes ("""") means a double quote.

Official article by Microsoft with full description on every token: about_Special_Characters.

# (hash sign)

Single line comment.

Example.

1
2
#This is a commented line
#This is a second one

> (right angle bracket)

Mike asked a question about this one.

Output redirection. See this article by Microsoft - it lists all possible use cases with examples.

Example - Send the list of active processes to a file.

1
Get-Process > processes.txt

<# … #> (left angle bracket / < + pound … pound + right angle bracket / >)

Block/Multi-line comment.

Example.

1
2
3
<#This is
a commented
block#>

& (ampersand)

Execute string as command.

Example.

1
& "Get-Process"

@( ) (email-at + round brackets)

Declare arrays.

Note: comma is used as a separator, in contrast to hash table declaration.

Example.

1
$a = @("One", "Two", "Three")

@{ } (email-at + curly brackets/braces)

Thanks to Marek for a suggestion to add parameter splatting use case.

Declare hash tables. Powershell 2.0 introduced a new feature called parameter splatting, which is one of the nice uses for hash tables.

It allows you to supply dynamic values and number of arguments to an otherwise static call of the function (see Example 2 below).

Note: semicolon is used as a separator, in contrast to array declaration.

Example 1 - Declare hash table and get item by key.

1
2
3
4
5
$a = @{"1" = "one";
       "2" = "two";
       "3" = "three"}

$a["2"] #prints "two" (without quotes)

Example 2 - Declare empty hash table, populate with arguments, and use parameter splatting.

1
2
3
4
5
6
$params = @{};
$params['class'] = 'Win32_DiskDrive';
$params['filter'] = 'size=256052966400'; #find a drive which is 256GB in size

Get-WmiObject @params
#identical to Get-WmiObject -Class 'Win32_DiskDrive' -Filter 'size=256052966400'

@’ … ‘@ (email-at + single quote … single quote + email-at)

Multi-line string literal without embedded variables.

Code.

1
2
3
4
5
@'
$(1+2)
$(3+4)
$(5+6) 
'@

Output.

$(1+2)
$(3+4)
$(5+6)

@" … “@ (email-at + double quote … double quote + email-at)

Multi-line string literal with embedded variables.

Code.

1
2
3
4
5
@"
$(1+2)
$(3+4)
$(5+6)
"@

Output.

3
7
11

0x (zero x + number)

Added on request from Michael.

Specify a number in hexadecimal form.

Example.

1
0x10

Output.

16

Note 1. You can use this notation to specify Unicode characters.

Example.

1
[char]0x0048

Output.

H

Note 2. You can embed Unicode characters into a string, combining this and $() notation (described prior on this page):

Example.

1
"Some Company $([char]0x00AE)"

Output (In some versions of Powershell, the console will display ® as R - you can use PowerShell ISE to verify).

Some Company ®		

Number + KB, MB, GB, TB or PB

Apoorv suggested to mention this feature.

Powershell understands standard notation for kilobytes, megabytes, gigabytes, terabytes and even petabytes.

Code.

1
@(1KB, 1MB, 1GB, 1TB, 1PB)

Output.

1024
1048576
1073741824
1099511627776
1125899906842624

Victor Zakharov
WRITTEN BY
Victor Zakharov
Web Developer (Angular/.NET)