Replace variable in all fldrs and subfldrs with ext .cfg

by scifidad71 at 2012-12-08 07:37:25

I’m new to powershell so any help would be greatly appreciated! I’m looking for a simple way to replace a variable in multiple .cfg files in all subfolders. I have a basic example that works but I would have to list all paths for all of the .cfg
files in all folders and subfolders.

[int]$x = 999

(Get-Content C:\Users\Myself\Desktop\Testfolder\testfile5.cfg) | ForEach-Object { $_ -replace “STR$x”, “ST$x-sql-01? } | Set-Content

There are quite a few .cfg files in many folders and subfolders. How can I replace the above variable to all folders and subfolders?

I can read all files and within all subfolders using the below command, but I cannot Replace the variable within it.

[int]$x = 999
Get-ChildItem C:\Users\Myself\Desktop\Testfolder –recurse -include *.cfg | Get-Content

Again, the above command will list all of the info from all folders and subfolders. What do I need to add to this to Replace the variable?
by DonJ at 2012-12-08 08:44:09
You’ve already got both pieces, you’re just not putting them together! Actually, it’s a bit tricky. What you want to do is handle each file itself, that way you’ll have access to its filename.

[int]$x = 999
Get-ChildItem C:\Users\Myself\Desktop\Testfolder –recurse -include *.cfg |
ForEach-Object {
$filename = $.fullname
$content = Get-Content $
$content | Out-File $.fullname

Sometimes trying to cram everything into a one-liner actually makes it harder to write, and the logic harder to follow. This approach is a bit more step-by-step.
by nohandle at 2012-12-08 08:51:54
[int]$x = 999
Get-ChildItem c:\temp\cfgs -Recurse -Include *.cfg |
foreach {
#load file contents
$content=Get-Content -Path $
#modify file contents
$content= $content -replace [regex]::Escape(“STR$x”),“STR$x-sql-01”
#save the file
Set-Content -Path $_.fullname $content
by nohandle at 2012-12-08 08:53:32
huh, looks like I was to slow typing it. :smiley:
Don: you create Filename variable but you don’t use it aterwards.
by DonJ at 2012-12-08 08:55:32
Yeah, good point.
by scifidad71 at 2012-12-08 15:25:22
Thank you both! I will try this ASAP, thanks again for your help.