繁体   English   中英

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

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

我很喜欢函数如何能够大大减少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似乎在执行函数时遇到问题,我得到'你必须在'+'运算符的右侧提供一个值表达式。 表达式或语句中的'意外的标记'val'。 错误。

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

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

"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"

暂无
暂无

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

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