#PowerShell set-content cannot access the file

gc file.txt | % {$_ -replace ‘xxx’, ‘yyy’} | sc file.txt
(gc file.txt) | % {$_ -replace ‘xxx’, ‘yyy’} | sc file.txt

These two commands are completly different. The first one will not work with the error message “The process cannot access the file…” When you try to set the content of the file after processing the first line, we still have it open so that we can send you the second line. To tackle with this problem we need to load the entire content of the file into memory before making any changes. The second command does it.