0
PS> 'abcjjadjjnamndabc' -replace 'abc', '$$' 
PS> 'abcjjadjjnamndabc' | foreach { $_ + " end of statement" }

I have above 2 statements which can run independently, but I want to do this action in one attempt.

I did try something like below, but syntax is failing.

PS> 'abcjjadjjnamndabc' | foreach { $_ + "end of statement" } |-replace 'abc', '','' 
2
  • Wrap your pipeline in parenthesis to make it an expression with a return that -replace can work with: ('stringhere' | % {$_ + 'end'}) -replace 'abc' Commented Jul 24, 2018 at 16:04
  • Alternatively: 'abcjjadjjnamndabc' | ForEach-Object { "$_ end of statement" -replace 'abc' } Commented Jul 24, 2018 at 16:06

1 Answer 1

4

Your main problem is that -replace is not a function, cmdlet or method. It's a PowerShell Operator and that means you cannot do |-replace 'abc', '' to pipe into it.

There are many ways you can combine these, the simplest is to swap the order and do the replace first:

'abcjjadjjnamndabc' -replace 'abc', '' | foreach { "$_ end of statement" }

Or to wrap the pipeline in parentheses, and do the replace on the result of that:

('abcjjadjjnamndabc' | foreach { "$_ end of statement" }) -replace 'abc', ''

Or (if you're not using regular expressions in the search/replace) to chain these similar methods:

'abcjjadjjnamndabc'.Replace('abc', '').ForEach({"$_ end of statement"})
Sign up to request clarification or add additional context in comments.

1 Comment

Note the second argument to -replace is optional if your goal is to delete text.

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.