且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用扩展字符串作为 Powershell 函数参数

更新时间:2023-02-03 09:16:40

出现您的问题是因为 $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).