When you need to show a PowerShell variable in a string, you typically just add the variable along with some other text inside of a string with double-quotes as shown below
Related: Back to Basics: PowerShell Strings
Putting a variable inside of a double-quoted string is called variable expansion. This method of variable insertion is fine if the variable in question has a value.
But what if the string is part of a larger script and you have various conditions that might set
$serverName. This means that the variable might not contain any value at all. At that point, your message just looks messed up.
You can see below if you just insert the PowerShell variable inside of the string and then return the value, nothing is shown. You have no way to know if that value even contained a variable reference at all!
The solution? Make it a habit of enclosing your variables inside of strings with simple brackets.
You can now clearly see that a variable should have been there but was not.
It’s a simple trick but it’s saved me so much troubleshooting time over the years. Now, it’s habit to enclose variables in brackets. In fact, I have a snippet that I use to simply type
varb and it will automatically do it for me.
More from Adam The Automator & Friends
Find out how many of your Active Directory users are using leaked passwords by running a free read-only scan with Specops Password Auditor.
Why not write on a platform with an existing audience and share your knowledge with the world?
We've put together a list of the resources we, at ATA, can wholeheartedly recommend.