What Can You Do With ${MyVariable} In PowerShell?

Dollar sign is used for declaring the variable. Typically, variable names do not contain spaces and are following the camelCase notation. Please refer to about_variables for more information.

But (there is always but isn’t it) using something else than camel case or even use of special characters is not forbidden.

PowerShell is very flexible and there are a lot of things you can do with it, it does not necessarily means that you should, though. Using space (or any special character of that matter) in the variable name would be one of those. Here is the list of PowerShell special characters along with their usage and examples:

So for that specific case PowerShell team added the ${MyVariable} functionality which allows you to have all the special characters in the variable name.

${$$$}="3 dollar signs"
${+=* &%}="plus equal wildcard space ampersand percentage"
${::}=${$$$}+"|"+${+=* &%}

In addition to the ability to use space and the other special characters in the variable name, dollar sign curly braces has more to offer.

Before we are going to go ahead and explore what we can do with ${MyVariable} notation, let’s take a short step back and get on the same page in regards of different variable categories in PowerShell.

PowerShell Variable Categories

As you can see from the picture ${ } falls under the Variables on Providers Drives category. Let’s take one more side route (it is the last one I promise) and get a refresher on PowerShell Provides and Drives.

PowerShell Provides and Drives

Each provider expose data on drive and it is accessed via a path just like with a disk drive.

Here is the list of Providers and their respective drives:

OK, now we are ready to get back on the main track and discuss the gist of the article.

The Variable Syntax

If the name that you specified inside the curly braces is a valid drive-qualified path, then you can use it a shortcut to get data from the file or to put data into it. This specific notation is called – the variable syntax. It is implemented using the IContentCmdletProvider, small caveat it is not implemented for all of the providers.

Alias Provider

Get-ChildItem alias:
$alias=${alias:cls}
$alias
& $alias

Environment Provider

$processors=${env:NUMBER_OF_PROCESSORS}
$processors

FileSystem Provider

$file=${C:\users\andys\output.json}
1..5 | %{"line#$_" | out-file myArray.txt -Append}
cat .\myArray.txt
${c:myArray.txt}+="line#6"

Function Provider

get-childitem function: | select -First 8
$cls=${function:clear-host}
$cls

Variable Provider

get-childitem variable: | select -First 8
${variable:alias}+="2"
$alias

Thanks a lot for reading.

Please let me know some of the use case that you find ${ } to be useful in the comments section below.

Reference(s)

Leave a 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.