Powershell替换函数奇怪的行为

时间:2012-04-25 07:43:19

标签: string powershell

一个简单的例子,我不知道如何让它工作......

 function replace($rep, $by){ 
    Process { $_ -replace $rep, $by }
}

当我做的时候

"test" | replace("test", "foo")

结果是

test

当我这样做时

 function replace(){ 
    Process { $_ -replace "test", "foo" }
}

"test" | replace()

结果是

foo

任何想法?

2 个答案:

答案 0 :(得分:3)

PowerShell中的函数遵循与cmdlet和本机命令相同的参数规则,即参数由空格分隔(是的,这也意味着您不需要引用您的参数,因为它们会自动解释为字符串解析模式):

'test' | replace test foo

因此,如果您在括号中调用带有参数的PowerShell函数或cmdlet,您将获得一个参数,该参数是函数中的数组。 方法对对象的调用遵循其他规则(看起来与C#大致相同)。

详细说明:PowerShell有两种不同的模式,用于解析一行:表达式模式命令模式。在表达式模式下,PowerShell的行为类似于REPL。您可以输入1+1并返回2,或输入'foo' -replace 'o'并获取f。命令模式用于模仿shell的行为。那是你想要运行命令的时候,例如Get-ChildItem& 'C:\Program Files\Foo\foo.exe' bar blah。在括号内,模式确定重新开始,这就是Write-Host (Get-ChildItem)Write-Host Get-ChildItem不同的原因。

答案 1 :(得分:0)

删除函数调用中的()和remove comma

"test" | replace "test" "foo"