0

I am trying to find and replace a strings in a file and then saving it to the original file in PowerShell.

I've tried doing

(Get-Content "C:\Users\anon\Desktop\test.txt") 
-replace 'apple', 'apple1'
-replace 'bear' , 'bear1' |
Out-File test1.txt
pause

However, I keep getting

-replace : The term '-replace' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At C:\Users\Xing Chen\Desktop\test.ps1:2 char:1
+ -replace 'apple', 'apple1'
+ ~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (-replace:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I've been able to use "abcd".replace() fine and according to the documentation -replace should work too.

3
  • 5
    If you put the -replace operator in a new line without escaping the line break PowerShell will interpret (Get-Content "C:\Users\anon\Desktop\test.txt") as a complete statement and -replace 'apple', 'apple1' as another statement (with a command it doesn't recognize. Put the -replace operations on the same line as Get-Content and the problem will disappear. Commented Dec 14, 2017 at 17:40
  • @AnsgarWiechers - Propose this as an answer; it will solve the querent's issue. Commented Dec 14, 2017 at 17:54
  • @JeffZeitlin I consider this a case of "simple typographic error" and voted to close. Commented Dec 14, 2017 at 18:40

1 Answer 1

1

There is nothing in your code to represent the line continuations and the interpreter is not seeing the -replace operators as part of the same command. You have two options to resolve this: escaping the newlines or putting the commands on the same line.

@(Get-Content "C:\Users\anon\Desktop\test.txt") -replace 'apple','apple1' -replace 'bear','bear1' |
    Out-File -FilePath test1.txt
Pause

OR

@(Get-Content "C:\Users\anon\Desktop\test.txt") `
-replace 'apple','apple1' `
-replace 'bear','bear1' |
    Out-File -FilePath test1.txt
Pause
Sign up to request clarification or add additional context in comments.

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.