Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String Powershell替换函数异常行为_String_Powershell - Fatal编程技术网

String Powershell替换函数异常行为

String Powershell替换函数异常行为,string,powershell,String,Powershell,一个简单的例子,我不知道如何让它工作 function replace($rep, $by){ Process { $_ -replace $rep, $by } } 当我这样做的时候 "test" | replace("test", "foo") 结果是 test foo 当我这样做的时候 function replace(){ Process { $_ -replace "test", "foo" } } "test" | replace() 结果是 te

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

 function replace($rep, $by){ 
    Process { $_ -replace $rep, $by }
}
当我这样做的时候

"test" | replace("test", "foo")
结果是

test
foo
当我这样做的时候

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

"test" | replace()
结果是

test
foo
有什么想法吗?

删除函数调用中的(),然后单击


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

因此,如果使用括号中的参数调用PowerShell函数或cmdlet,则会得到一个参数,该参数是函数中的数组。对象上方法的调用遵循其他规则(与C#中的规则大致相同)


再详细说明一下:PowerShell有两种不同的模式来解析行:表达式模式和命令模式。在表达式模式下,PowerShell的行为类似于REPL。您可以键入
1+1
并返回
2
,或者键入
'foo'-替换'o'
并返回
f
。命令模式用于模拟shell的行为。这时您需要运行命令,例如,
getchilditem
&'C:\programmfiles\Foo\Foo.exe'条等等。括号内模式确定重新开始,这就是为什么
写入主机(Get ChildItem)
不同于
写入主机Get ChildItem

谢谢!昨天启动了powershell,我缺乏这方面的基础。一开始可能会有点混乱,特别是来自类C语言或Unix shell,但语言设计者做了细致的工作,以便您可以学习一些概念,并在使用powershell的过程中重新应用它们。一个小提示:
filter
的行为与
function
具有
进程
块的行为相同,因此您可以将代码稍微简化为
filter replace($rep,$by){$\ replace$rep,$by}
来自c#有时有点令人困惑,但powershell似乎是无法读取的vbs脚本或c#编译的应用程序的强大替代品。过滤器尖端的thx!