问题描述
我正在尝试编写一个函数,该函数将打印针对用户提供的姓名的用户提供的问候语.我想在此代码块中以我可以使用的方式使用扩展字符串:
I'm trying to write a function that will print a user-supplied greeting addressed to a user-supplied name. I want to use expanding strings the way I can in this code block:
$Name = "World"
$Greeting = "Hello, $Name!"
$Greeting
成功打印Hello, World!
.但是,当我尝试将这些字符串作为参数传递给这样的函数时,
Which successfully prints Hello, World!
. However, when I try to pass these strings as parameters to a function like so,
function HelloWorld
{
Param ($Greeting, $Name)
$Greeting
}
HelloWorld("Hello, $Name!", "World")
我得到输出
Hello, !
World
经调查,Powershell 似乎完全忽略了 "Hello, $Name!"
中的 $Name
,运行
Upon investigation, Powershell seems to be ignoring $Name
in "Hello, $Name!"
completely, as running
HelloWorld("Hello, !", "World")
产生与上面相同的输出.此外,它似乎没有将 "World"
视为 $Name
的值,因为运行
Produces output identical to above. Additionally, it doesn't seem to regard "World"
as the value of $Name
, since running
function HelloWorld
{
Param ($Greeting, $Name)
$Name
}
HelloWorld("Hello, $Name!", "World")
不产生任何输出.
当作为函数参数传入时,有没有办法让扩展字符串起作用?
Is there a way to get the expanding string to work when passed in as a function parameter?
推荐答案
出现您的问题是因为 $Name
字符串替换发生在函数外部,在 $Name
变量填充在函数内部.
Your issue occurs because the $Name
string replacement is happening outside of the function, before the $Name
variable is populated inside of the function.
你可以这样做:
function HelloWorld
{
Param ($Greeting, $Name)
$Greeting -replace '\$Name',$Name
}
HelloWorld -Greeting 'Hello, $Name!' -Name 'World'
通过使用单引号,我们发送 Hello, $Name
的字面问候,然后在函数内部使用 -Replace
替换这个字符串(我们有将 \
放在我们要替换的字符串中的 $
之前,因为 $
是正则表达式特殊字符).
By using single quotes, we send the literal greeting of Hello, $Name
in and then do the replacement of this string inside the function using -Replace
(we have to put a \
before the $
in the string we're replace because $
is a regex special character).
这篇关于使用扩展字符串作为 Powershell 函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!