Using special characters in PowerShell Variables

PowerShellPowerShell is an important part of today’s IT landscape. By using PowerShell you can manage systems from different vendors in a unified way. Nowadays more and more vendors come with there own PowerShell cmdlets, PowerShell is way more than just another tool for today’s sysadmins. Today more then ever IT pros should me getting onboard the PowerShell train. It reminds me of a presentation I saw a couple of years ago where the presenter urged the attendees to ether learn PowerShell today or learn how to say the phrase “Do you want to have fries with that?”.

I am not sure if it is going to be like that. If you like scripting, learning PowerShell can be allot of fun. People often ask how to start learning PowerShell since there is so much to learn and there is allot of content on the subject online. My advice if you want to learn PowerShell today would be:

This is a good way to learn the fundamental basics and guide you through the first steps in the world called PowerShell.

Today I want to talk about naming your variables, you want the name to identify its purpose so you can still tell what it does when you revisit your script a year later.

What characters can you use for naming a variable? To start off you can use all the alphanumeric characters, both capital letters and small letters.

But what happens if I want to include a hyphen in my PowerShell variable name?

In the above image you can see that I have tried various options to defined my variable “my-variable”.

I found to following solution to solve my issue.

image By using the curly brackets after the $ sign and at the end of the variable name, I am able to add special characters to my variable name. Those curly brackets should be used every time when calling the variable in your code.

Other special characters you can use are the following:
$my_variable (please note that you can use an underscore in a variable name without using curly brackets)

Stay calm and happy coding.


Leave a Reply