Search code examples
powershellscriptingreplacefind

PowerShell Script to Find and Replace for all Files with a Specific Extension


I have several configuration files nested like such:

C:\Projects\Project_1\project1.config
  
C:\Projects\Project_2\project2.config

In my configuration I need to do a string replace like such:

<add key="Environment" value="Dev"/>

will become:

<add key="Environment" value="Demo"/>

I thought about using batch scripting, but there was no good way to do this, and I heard that with PowerShell scripting you can easily perform this. I have found examples of find/replace, but I was hoping for a way that would traverse all folders within my C:\Projects directory and find any files that end with the '.config' extension. When it finds one, I want it to replace my string values.

Any good resources to find out how to do this or any PowerShell gurus that can offer some insight?


Solution

  • Here a first attempt at the top of my head.

    $configFiles = Get-ChildItem . *.config -rec
    foreach ($file in $configFiles)
    {
        (Get-Content $file.PSPath) |
        Foreach-Object { $_ -replace "Dev", "Demo" } |
        Set-Content $file.PSPath
    }