构建一个字符串参数以函数 - PowerShell
我想知道如何即时构造字符串作为函数的参数? 例子 假设我有一个功能,例如
function MyFunc
{
Param
(
[Parameter(mandatory=$true)] [string] $myString,
[Parameter(mandatory=$true)] [int] $myInt
)
Write-Host ("Param 1 is {0}" -f $myString)
Write-Host ("Param 2 is {0}" -f $myInt)
}
我如何称呼它,而在fly上构造第一个字符串参数,例如
$myName = "Casper"
$myInt=7
MyFunc "Name is " + $myName $myInt
我试图将{}放在第一个“ bit”上
MyFunc {Name is " + $myName} $myInt
,然后错误地打印出
Param 1 is "Name is "+$myName
Param 2 is 7
我想打印的内容,
Param 1 is "Name is Casper"
Param 2 is 7
我知道我知道更好的方法这样做的只是首先设置字符串,
$pm1 = "Name is " + $myName
然后调用功能 myfunc $ pm1 $ myint
,但我只是想知道它可以像以前一样即时完成。如何构造字符串并将其作为函数调用上的第一个参数传递?希望那很清楚。
谢谢
Im wondering how you can construct a string on the fly as a parameter to a function?
Example
say I have a function like
function MyFunc
{
Param
(
[Parameter(mandatory=$true)] [string] $myString,
[Parameter(mandatory=$true)] [int] $myInt
)
Write-Host ("Param 1 is {0}" -f $myString)
Write-Host ("Param 2 is {0}" -f $myInt)
}
How can I call it whilst constructing the first string param on the fly e.g.
$myName = "Casper"
$myInt=7
MyFunc "Name is " + $myName $myInt
Ive tried putting {} around the first "bit" like
MyFunc {Name is " + $myName} $myInt
This then incorrectly prints out
Param 1 is "Name is "+$myName
Param 2 is 7
what I want it to print is
Param 1 is "Name is Casper"
Param 2 is 7
I know a better way of doing this would just be to set up the string first,
$pm1 = "Name is " + $myName
and call function
MyFunc $pm1 $myInt
but I am just interested to know how it can be done on the fly as it were. How can I construc the string and pass as first parameter on the function call? Hope thats clear.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为一般的经验法则,您可以随时使用子表达操作员
$(...)
或分组操作员(...)
分组操作员 ,您始终可以在单独的管道中嵌套任何复杂的表达式。 :但是,在您的特殊情况下,我们不需要 - 您只需要在字符串文字中放置变量表达式
$ myname
,并且PowerShell将自动评估和扩展其值:如果变量表达式是紧随其后的是一些字符,否则这些字符将构成变量路径的有效部分,使用curly括号
{}
作为预选赛:As a general rule of thumb, you can always nest any complex expression in a separate pipeline using the subexpression operator
$(...)
or grouping operator(...)
:But in your particular case we don't need that - you just need to place the variable expression
$myName
inside the string literal and PowerShell will automatically evaluate and expand its value:If the variable expression is to be followed by some characters that would otherwise make up a valid part of the variable path, use curly brackets
{}
as qualifiers: