简体   繁体   English

Powershell中的函数 - 它们可以在字符串中调用吗?

[英]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. 我很喜欢函数如何能够大大减少Powershell脚本中的繁忙工作,并且它们为我节省了大量的冗余编码。 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. 但我现在遇到在Powershell字符串中调用声明函数的问题(作为使用'+'符号的连接字符串的一部分)并且想知道是否有这样做的技巧。 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.' Powershell似乎在执行函数时遇到问题,我得到'你必须在'+'运算符的右侧提供一个值表达式。 and 'Unexpected token 'val' in expression or statement.' 表达式或语句中的'意外的标记'val'。 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. 另外值得指出的是,PowerShell中的命令调用语法不需要括号。 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: 现在,使用类似C#的语法,您可以:

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. 因为PowerShell解析器会看到嵌套表达式("first","second")并将其视为单个参数。

The correct syntax for positional parameter arguments would be: 位置参数参数的正确语法是:

val "first" "second"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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