16

I have a .txt file in which I want to replace the string aaa with bbb.

I have tried the following PowerShell code:

Get-Content c:\1.txt | ForEach-Object { $_ -replace "aaa", "bbb" } | Set-Content c:\1.txt

I get an error that 1.txt is being used by another process. What am I doing wrong?

Indrek
  • 24,874

1 Answers1

22
(get-content c:\1.txt) | foreach-object {$_ -replace "prod", "qa1"} | set-content c:\1.txt

The parentheses around Get-Content ensure that the Get operation is completed before the Set operation begins, without this the two functions would both try to access the file at the same time.

Indrek
  • 24,874