简体   繁体   中英

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

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:

#this function takes input and either returns the input as the value, or returns 
placeholder text as the value

function val ($valinput)
{ if ($valinput)
   {return $valinput}
   else
   {$valinput = "No Results!"; return $valinput}
}

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

val("yo!")

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

"The results of the tests are: " + val($results)

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...!

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

"The results of the test are: $(val "yo!")"

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:

function val ($inputOne,$inputTwo)
{
    "One: $inputOne"
    "Two: $inputTwo"
}

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

val("first","second")

but find that the output becomes:

One: first second
Two: 

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:

val "first" "second"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM