Beginner PowerShell Tip: Using Variable Properties In Strings

If you’re just getting started in PowerShell, it’s possible that you haven’t bumped into this specific issue yet. Say you’ve got a variable named $user and this is how you assigned a value to it.

Using the Active Directory module, you got a specific user. Now, you want to report two properties back to the end user: SamAccountName and Enabled. The desired output looks like this:

So, you try something like this.

And you’ll get something totally unexpected!

Whaaaat? That’s not what we want. What happened? It looks like I got the distinguished name of the user and then literally “.SamAccountName” and “.Enabled”. Doesn’t PowerShell know that I actually want the SamAccountName and Enabled properties?

Well, the short answer is no, PowerShell doesn’t know that. What if you had a variable $domain set to “workingsysadmin” and wanted to do Write-Output “$” to get “” written out? PowerShell doesn’t know if you’re trying to access a property on the variable, or work with .com (or .SamAccountName or .Enabled) as a literal string.

So what do we do? We’ll use some brackets.

This will give the desired output. What we’ve done is use $( ) to tell PowerShell that we want to evaluate the entire expression wrapped in those brackets, and use that in our string.

One thought on “Beginner PowerShell Tip: Using Variable Properties In Strings

Leave a Reply

Your email address will not be published. Required fields are marked *