Ask anyone who have worked with PowerShell for a while, and they will all tell you to try to avoid spaces and special characters in variable names and property names of custom objects or hash tables. Even though it’s possible to use them, there is a reason why it’s not recommended, but unfortunately you might come up in a situation where such things are out of your control, and you just have to deal with it.
In this quick tip I will show you how to handle variable names and property names with spaces and special characters.
As you know, variables are represented as text strings that begin with a dollar sign ($). Consider you have to deal with a variable with the name of ‘my-variable‘, how would you get at the value of this variable?
The following approach, which you normally would use, results in an error:
There are two approaches that you can use :
As you see in the screenshot above, the first approach is to wrap the variable name in curly-brackets, and the second approach is to use the Get-Variable command. If you want just the value, enclose the command in parenthesis and reference just the Value property.
NOTE! If you want to create a variable with special characters, you could use the Set-Variable command or use the curly-bracket variant.
NOTE2! It’s important to note that ‘$variableName’ refers to the value of the variable while ‘variableName’ refers to the name of the variable. That’s why we don’t use the dollar sign when we are using the *-Variable commands.
Let’s make a custom object that we can test with.
First let me point out than when declaring an object, you need to enclose the strings with quotation marks for the properties that have spaces and special characters in them. Failing to do so will again result in an error.
Having an object, we know we can reference individual properties like this:
But see what happens for the property names with space and a special character!
The solutions is to wrap them in quotation marks of course, same as we had to do when we created the object.
With Hash Tables we can reference individual key values the same way we would reference properties in an object. And, as with objects, if we have key names with space or special characters, we need to wrap them in quotation marks to be able to use them. But I’m going to show you two alternate ways of referencing keys in a Hash Table:
The first two examples you recognize from the object example, but the last two you see the alternate ways of referencing a key in a Hash Table, both of which handles special characters in a more understandable way, as the strings needs to be quoted for these methods to be successful.
I hope this small quick tip was helpful. If you spot any errors, or have any comments, don’t hesitate to let me know!