Powershell string concatenation of expressions

I'm using a ternary expression as shown in this example:

$a = 1
$x = if ($a -eq 1) { "one" } else {"not one" }
$t = "The answer is: " + $x
write-host $t

This works as I would expect. What I would like to do in my real situation though, is to assign directly to $t without the intermediate step of first assigning the expression to $x, as if I could do this:

$a = 1
$t = "The answer is: " + (if ($a -eq 1) { "one" } else {"not one" })
write-host $t

However, I get an error on the assignment line,

if : The term 'if' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:31
+ $t = "The answer is: " + (if ($a -eq 1) { "one" } else {"not one" ...
+ ~~ + CategoryInfo : ObjectNotFound: (if:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException

(I've tried with an without the (...) brackets: same error.) Clearly I'm doing something wrong, but my google-fu isn't helping today. I can see how to concatenate constants and variables, but nothing seems to explain how to concatenate constants and expressions.

Can you point me in the right direction, please?

1 Answer

You're so close. :)

You need to use the $ to declare the statement's return value as a variable.

So:

$a = 1
$t = "The answer is: " + $(if ($a -eq 1) { "one" } else { "not one" })
write-host $t

Or perhaps as two lines, utilizing Write-Host's formatting options:

$a = 1
write-host ("{0} {1}" -f "The answer is:", $(if ($a -eq 1) { "one" } else { "not one" }))
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like