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

时间:2017-05-17 22:47:47

标签: function powershell powershell-v2.0 powershell-v3.0 string-concatenation

我很喜欢函数如何能够极大地减少Powershell脚本中的繁忙工作,并且它们为我节省了大量的冗余编码。但我现在遇到在Powershell字符串中调用声明函数的问题(作为使用'+'符号的连接字符串的一部分)并且想知道是否有这样做的技巧。一些示例代码:

#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}
}

如果我在行的开头或单独调用该函数:

val("yo!")

运行正常。但是,如果我尝试将其连接为字符串的一部分,例如:

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

Powershell似乎在执行那里的功能时遇到了问题,而我 get '您必须在右侧提供值表达式 表达式中的'+'运算符。''意外标记'val' 陈述。'错误。

有没有办法正确调用连接字符串中的函数?我知道我可以将函数的结果推送到另一个变量并将结果变量连接为字符串的一部分,但每次调用此函数时都会很麻烦。在此先感谢...!

1 个答案:

答案 0 :(得分:11)

将命令/函数调用包装在可扩展字符串内的子表达式中:

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

另外值得指出的是,PowerShell中的命令调用语法并不需要括号。我会劝阻使用括号,就像你在示例中一样,因为你最终会将连续的参数视为一个:

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

现在,使用类似C#的语法,您可以:

val("first","second")

但发现输出变为:

One: first second
Two: 

因为PowerShell解析器看到嵌套表达式("first","second")并将其视为单个参数。

位置参数参数的正确语法是:

val "first" "second"