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 执行那里的功能似乎有问题,我
get '你必须在右边提供一个值表达式
'+' 运算符。' 和 '表达式中的意外标记 'val' 或
语句。' 错误。
有没有办法在连接的字符串中正确调用函数?我知道我可以将函数的结果推送到另一个变量并将结果变量连接为字符串的一部分,但每次调用此函数时都这样做会很麻烦。提前致谢...!
将 command/function 调用包装在可扩展字符串内的子表达式中:
"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"
我很喜欢函数如何极大地减少 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' 或 语句。' 错误。
有没有办法在连接的字符串中正确调用函数?我知道我可以将函数的结果推送到另一个变量并将结果变量连接为字符串的一部分,但每次调用此函数时都这样做会很麻烦。提前致谢...!
将 command/function 调用包装在可扩展字符串内的子表达式中:
"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"