1

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 $_
}

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

Ok, I tried using ` but still it's not replacing the string.
tried with your updated script but still, it's not replacing the content. And after running your script, it prints file content on PowerShell ISE console, I don't want to print that.
One more thing SomeFolder contains some subfolders and it also contains mke files. Currently, it's only working at the root level. So how to make replacement in a subfolder?
I created a folder with 2 level of subfolders, each with the same file. Tested the same code and it updates all the files.
@Rudra see my update in the post. I did a get-childitem and it shows all the files. I did get-content on each file as well and they all show updated content.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.