In the first strand of our series on strings we covered the basics. Now that you’re feeling comfortable, let’s enter the Twilight Zone and pass through a black hole and get sucked into the Upside Down. In Part 2, we’re going to look at some of the other cool ways we can work with PowerShell strings. We’ll go over combining strings, the escape character, expressions, and then putting it all together to build an expression to use with Invoke-Expression.

Everytime I look down and see my empty coffee cup, I always wonder where my coffee went…now I know.

\\\Unraveling Strings

So we’ve talked about calling variables inside double quotations, but we can also use expressions in our strings. Remember from Part 1 where we can use the subexpession operator $() and then put the stuffing in between the two slices of bread? No? Who cares, let’s try one:

PowerShell String with Expression

Well, that’s kind of right but it includes the date and the time. With inaccuracies like this, we’re sure to get eaten up when our theory is peer-reviewed. We can also use dot notation here and utilize the method ToShortTimeString(). That way we only get the time itself and not the date.

PowerShell String with Expression 2

Basically, you can evaluate expressions when defining the string instead of doing it before hand and storing it in a variable. Neato!

\\\Multiple Strings

–Add (Not The Disorder)

Hopefully you’re not strung out at this point, but just like angel hair pasta, we can add strings together to make one big bowl-o-string.  This is useful if you want to do something like combine a username with a DNS suffix to get a UserPrincipalName:

PowerShell Combining Strings 1
–Single & Double Patties

And if you’re wondering, we can even mix single quotations and double quotations:

PowerShell Combining Strings 2
–Old + New

Call us butter ’cause we’re on a roll! We can add a string to an existing variable that’s storing a string as well. Notice that the string stored in $String is replaced with our new text when we update the value of the variable again. In this case, the old value of $String is added with our new text to make a string that would make the good doctor proud:

PowerShell Combining Strings 3
–The Shortcut

And the last trick we can use when combining strings if the nifty shortcut by using the assignment operator +=. This will append the new value with the existing value in $String:

PowerShell Combining Strings 4

\\\Escape Velocity

What if we want our string to contain literal single quotation marks in the string itself? Impossible!? (said with a Spanish flair) Nah, hold my coffee and watch this cyborg adhoc madness!

PowerShell Combining Strings 5

I mean…sure, that works, but there’s a better way.

That is not the way.

This is the way.

Over…here. You’re looking in the wrong…ah forget it.

The better way is made possible by another trick up the double quotation’s sleeve: the escape character. This is the little ` character to the left of the “1” on your keyboard that’s like a reverse apostrophe. Pretty sure if apostrophe was a super hero, this would be its arch nemesis. Apparently this little bugger is called the grave-accent, but it’s about to bring our scripts to life! (ba dum chtchh)

If you don’t want the character to be evaluated in the expression, just put the escape character before it when defining a string. This is really useful when you want your string to include a double quote:

PowerShell Escape Character

Noice! One-liner without the pluses.

\\\The Expression of Everything

The last part of our theory we want to postulate on today is when we want to build an expression that has a mix of variables and other literal characters. I find this useful when I want to build an expression out of a lot of variables but I want some evaluated and others referenced. This is beneficial when utilizing a nice little cmdlet called Invoke-Expression. This is the last straw string we’ll look at today.

First, lets look at the why. Maybe you want your expression to be dynamic and different based on tons of variables. Or maybe you’ll use Invoke-Command on a remote computer and want to build the expression ahead of time. I’ve created scripts in the past that would take 10-15 different parameters and I was feeding it thousands of objects to process. Rather than type out the cmdlet 10 or 15 different times in if/elseif statements, I would just add or remove from the string and then use Invoke-Expression at the end.

For our purposes today and just to serve as an example of the mechanics, this is a simple expression built as a string:

$Properties = "EmailAddress,Title"
$Expression = "Get-ADUser -Filter 'name -like `"*`$N*`"' -Properties $Properties"
Notice this expression has double quotations and a dollar sign that are escaped. We want $N to be literal and $Properties to be substituted with the value. Our $Expression now has this value:
Get-ADUser -Filter 'name -like "*$N*"' -Properties EmailAddress,Title
$N means nothing (man, that’s deep). But if we have an array of $Names, we can use this expression in a ForEach loop like so and then $N has value:
$Names = @('Hawking','Greene')
$Properties = "EmailAddress,Title"
$Expression = "Get-ADUser -Filter 'name -like `"*`$N*`"' -Properties EmailAddress"
ForEach($N in $Names){
	Invoke-Expression $Expression
}
Typically for something as straightforward as this, you would just type the cmdlet in the body of the ForEach loop, but there are scenarios where you would want to build the expression and invoke it. Especially if you’re building something modular and flexible.

Now that we’re strung out on strings, this is a good place to wrap up our theory. There are plenty of other things we can do with strings but we’ll save those for another spacetime.

OTHER POSTS YOU WANT TO READ

Index Scripts for Windows Search

So you just finished writing some code and you go to save your file. You summarize all of the important aspects this section of code contains into a nice, easy-to-read file name that your future self will immediately recognize. Fast forward to the future where you...

Array vs ArrayList (PowerShell)

For some tasks in life, being precise is a necessity. But most of us get away with rounding, paraphrasing, and hitting in the general vicinity most of the time. Depending on your personality, you may be one who strives for perfection and strains on every miniscule...

Spice Up HTML Emails with PowerShell – Part III

So far in this series we've fumbled our way around the kitchen and tried to wing it when sending HTML emails with PowerShell. It was clunky to say the least. We then went through our spice rack and built an HTML template, highlighting the nuances of each spicy element...

Spice up HTML Emails with PowerShell – Part II

In Part I of our scrumptious concoction we put our script into the oven to let it bake. But we forgot to add our secret sauce that's sure to leave our recipients drooling, which is clearly our goal. In this post we'll continue to spice up HTML emails with PowerShell...

Spice Up HTML Emails with PowerShell – Part I

I live in the South, specifically in God's country AKA TEXAS BABAY! There's plenty of amazing things about Texas and definitely some reasons to loathe being from Houston, but it's hard to knock our food. I mean, is there really even a debate between Whataburger vs...
%d