2

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 ?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks ! started powershell yesterday and I lack of that kind of basis.
It may be a bit confusing at first, especially coming from either C-like languages or Unix shells, but the language designers made careful effort so that you can learn a few concepts and reapply them throughout working with PowerShell. A minor hint: filter behaves the same as function with a process block, so you can simplify your code a little to filter replace ($rep, $by) { $_ -replace $rep, $by }
coming from c# is a bit confusing sometimes but powershell seems to be a very powerfull alternative to unreadable vbs scripts or c# compiled application. thx for the filter tip !
0

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

"test" | replace "test" "foo"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.