Rudra
Rudra

Reputation: 53

How do I find & replace file contents in PowerShell?

I need to find text in a file, like:

PolicyFile=$(SrcRoot)BeHttp

and replace it with this:

PolicyFile=$(SrcRoot)PPCore/BeHttp

So I wrote following script but it's not working.

Get-ChildItem 'D:\SomeFolder\\*.MKE' -Recurse | ForEach {
     (Get-Content $_ | ForEach  {   
       $_  -replace "PolicyFile=$(SrcRoot)BeHttp", "PolicyFile=$(SrcRoot)PPCore//BeHttp"
     }) | Set-Content $_
}

Upvotes: 1

Views: 106

Answers (1)

Jawad
Jawad

Reputation: 11364

You want to escape the characters powershell considers reserved. Also, when using Get-Content, you need to provide full path. That path is available under FullName of the Child Item (Get-ChildItem).

Get-ChildItem 'D:\SomeFolder\*.MKE' -Recurse | ForEach { 
        (Get-Content $_.FullName) -replace 'PolicyFile=\$\(SrcRoot\)BeHttp', 'PolicyFile=$(SrcRoot)PPCore//BeHttp' | Set-Content $_.FullName }

To Escape $ ( ), use \. Also, you dont need to use For-Each on string obtained from Get-Content.

Update:

When running Get-ChildItem, i do see all the files from all subfolders.

PS C:\Users\user> Get-ChildItem 'C:\Temp\*.MKE' -Recurse | % { $_.FullName}
C:\Temp\1\new.mke
C:\Temp\2\3\new.mke
C:\Temp\2\new.mke
C:\Temp\new.mke

Upvotes: 1

Related Questions