Functions in Powershell – can they be called within a string?

Question:

I’m loving how functions can vastly reduce the busywork within Powershell scripts, and they’ve saved me a ton of redundant coding. But I’m now having issues invoking a declared function within a Powershell string (as part of a concatenated string using ‘+’ sign) and wondering if there is a trick to doing this. Some sample code:

If I call the function at the beginning of the line or by itself:

It runs fine. But if I attempt to concatenate it as part of a string, for example:

Powershell seems to have problems executing the function there, and I
get ‘You must provide a value expression on the right-hand side of
the ‘+’ operator.’
and ‘Unexpected token ‘val’ in expression or
statement.’
errors.

Is there a way to properly call a function within the concatenated string? I know I can push the results of the function to another variable and concatenate the resulting variable as part of the string, but that would be cumbersome to do that each and every time I call this function. Thanks in advance…!

Answer:

Wrap the command/function call in a subexpression inside an expandable string:


Also worth pointing out, the syntax for command invocation in PowerShell doesn’t require parentheses. I would discourage using parentheses like you do in the example altogether, since you’ll end up in situations where consecutive arguments are being treated as one:

Now, using C#-like syntax, you’d do:

but find that the output becomes:

because the PowerShell parser sees the nested expression ("first","second") and treats it as a single argument.

The correct syntax for positional parameter arguments would be:

Source:

Functions in Powershell – can they be called within a string? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply