rbag
rbag

Reputation: 137

Powershell replace function strange behavior

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 ?

Upvotes: 2

Views: 459

Answers (2)

Joey
Joey

Reputation: 354506

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):

'test' | replace test foo

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+1 and get 2 back, or type 'foo' -replace 'o' and get f back. Command mode is for mimicking a shell's behaviour. That's when you want to run command, e.g. Get-ChildItem or & 'C:\Program Files\Foo\foo.exe' bar blah. Within parentheses mode determination starts anew which is why Write-Host (Get-ChildItem) is different from Write-Host Get-ChildItem.

Upvotes: 3

David Brabant
David Brabant

Reputation: 43499

Remove the () in your function call and remove comma.

"test" | replace "test" "foo"

Upvotes: 0

Related Questions