PowerShell Script to Find and Replace for all Files with a Specific Extension
Here a first attempt at the top of my head.
$configFiles = Get-ChildItem . *.config -recforeach ($file in $configFiles){ (Get-Content $file.PSPath) | Foreach-Object { $_ -replace "Dev", "Demo" } | Set-Content $file.PSPath}
PowerShell is a good choice ;) It is very easy to enumerate files in given directory, read them and process.
The script could look like this:
Get-ChildItem C:\Projects *.config -recurse | Foreach-Object { $c = ($_ | Get-Content) $c = $c -replace '<add key="Environment" value="Dev"/>','<add key="Environment" value="Demo"/>' [IO.File]::WriteAllText($_.FullName, ($c -join "`r`n")) }
I split the code to more lines to be readable for you.Note that you could use Set-Content instead of [IO.File]::WriteAllText
, but it adds new line at the end. With WriteAllText
you can avoid it.
Otherwise the code could look like this: $c | Set-Content $_.FullName
.
This approach works well:
gci C:\Projects *.config -recurse | ForEach { (Get-Content $_ | ForEach {$_ -replace "old", "new"}) | Set-Content $_ }
- Change "old" and "new" to their corresponding values (or use variables).
- Don't forget the parenthesis -- without which you will receive an access error.