Adding Numbers to a String (Part 1)

by Apr 12, 2019

Double-quoted strings can easily expand variables, however this concept is not foolproof:

$id = 123

# this is the desired output:
# Number is 123:
# this DOES NOT WORK:
"Number is $id:"

As you see in the sample above, when you place variables inside double-quoted text, PowerShell determines automatically where a variable starts and ends. A *** is considered part of the variable. To correct the issue, you need a way to clearly mark the start and end of a variable. Here are some approaches you can use to correct issues like this:

$id = 123

# PowerShell escape character ends the variable
"Number is $id`:"
# braces "embrace" the variable name
"Number is ${id}:"
# subexpressions execute the code in the parenthesis
"Number is $($id):"
# the format operator inserts the array on the right into the 
# placeholders in the template on the left
'Number is {0}:' -f $id
# which is essentially this:
'Number is ' + @($id)[0] + ':'

# careful with "addition": this requires the first 
# element to be a string. So this works:
'Number is ' + $id + ':'
# this won't:
$id + " is the number"
# whereas this will again:
'' + $id + " is the number"

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!