I am trying to go through all the files under a folder (‘C:\Users\thchen\Desktop\ReplaceTests’) to look for a particular string pattern (‘FindString’) and replace it with another (‘ReplaceString’) using the following code:
Get-ChildItem 'C:\Users\thchen\Desktop\ReplaceTests' -Recurse | ForEach { (Get-Content $_ | ForEach { $_ -replace 'FindString', 'ReplaceString' }) | Set-Content $_ }
Even if I copied the folder and placed it under a different location such as “C:\ReplaceTests” and reboot my PC
Get-ChildItem "C:\ReplaceTests" -Recurse | ForEach { (Get-Content $_ | ForEach { $_ -replace 'FindString', 'ReplaceString' }) | Set-Content $_ }
It would always gives me the following error:
Get-Content : Cannot find path ‘C:\windows\system32\SecondLayer’ because it does not exist.
At line:1 char:79
- … rs\thchen\Desktop\ReplaceTests -Recurse | ForEach {(Get-Content $_ )}
-
- CategoryInfo : ObjectNotFound: (C:\windows\system32\SecondLayer:String) [Get-Content], ItemNotFoundException
- FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
I don’t understand. I did not say anything about the folder "C:\windows\system32" anywhere in my code. Why is it going to that folder to look for a file?
And If I specify just one file using the codes below, it goes to the file, finds the pattern and replaces it without problem.
Get-Item -path C:\Users\thchen\Desktop\ReplaceTests\ReplaceTest.txt | ForEach { (Get-Content $_ | ForEach { $_ -replace 'FindString', 'ReplaceString' }) | Set-Content $_ }
Not sure what I am doing wrong. Anybody sees anything obvious that I am missing? Thanks for any help.