Zissou
Zissou

Reputation: 1

PowerShell -replace function

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.

Upvotes: 0

Views: 1515

Answers (1)

Maximilian Burszley
Maximilian Burszley

Reputation: 19684

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

Upvotes: 1

Related Questions