a simple example and i don’t know how to get it to work…
function replace($rep, $by){
Process { $_ -replace $rep, $by }
}
when I do
"test" | replace("test", "foo")
the result is
test
When I do
function replace(){
Process { $_ -replace "test", "foo" }
}
"test" | replace()
the result is
foo
any idea ?
Functions in PowerShell follow the same argument rules as cmdlets and native commands, that is, arguments are separated by spaces (and yes, this also means you don’t need to quote your arguments, as they are automatically interpreted as strings in that parsing mode):
So if you call a PowerShell function or cmdlet with arguments in parentheses you’ll get a single argument that is an array within the function. Invocations of methods on objects follow other rules (that look roughly like in C#).
To elaborate a little: PowerShell has two different modes in which it parses a line: expression mode and command mode. In expression mode PowerShell behaves like a REPL. You can type
1+1and get2back, or type'foo' -replace 'o'and getfback. Command mode is for mimicking a shell’s behaviour. That’s when you want to run command, e.g.Get-ChildItemor& 'C:\Program Files\Foo\foo.exe' bar blah. Within parentheses mode determination starts anew which is whyWrite-Host (Get-ChildItem)is different fromWrite-Host Get-ChildItem.