Reputation: 959
This is probably an easy one, but I'm trying to write a script to use when moving a directory for an installed program from one computer to another. In order to make this work, I have to find every instance of the old hostname, old IP address, and old drive letter from the old machine, and replace them with the new hostname, new IP address, and the new drive letter on the new machine. The primary folder contains *.xml and *.config files that need to be edited in the primary folder as well as in sub folders.
This is the code I'm working with:
$oldIP = "192.168.1.2"
$newIP = "192.168.1.3"
$oldhost = "OLDHOSTNAME"
$newhost = "NEWHOSTNAME"
$oldDriveLetter = "C"
$newDriveletter = "E"
$path = "\\$newip\$newdriveletter$\Folder"
$files = get-childitem $path\* -include *.xml, *.config, -recurse
$files | %{
(gc $_) -replace $oldhost, $newhost -replace $oldip, $newip -replace "${olddriveletter}:\Folder", "${newDriveLetter}:\Folder" | set-content $_.fullname
}
Currently, it is only replacing the values in the primary folder, but not any of the sub folders. Any idea what I'm missing?
Edit: Per the suggestion below, I removed the comma after *.config, and that seems to get me through the sub folders. But it's still not replacing any instance of C:\Folder with E:\Folder
Upvotes: 0
Views: 371
Reputation: 27423
This works fine. Took the comma off the end of *.config, and added another \ in the middle of ${olddriveletter}:\Folder.
$oldIP = "192.168.1.2"
$newIP = "192.168.1.3"
$oldhost = "OLDHOSTNAME"
$newhost = "NEWHOSTNAME"
$oldDriveLetter = "C"
$newDriveletter = "E"
$path = "."
$files = get-childitem $path\* -include *.xml, *.config -recurse
$files | %{
(gc $_) -replace $oldhost, $newhost -replace $oldip,
$newip -replace "${olddriveletter}:\\Folder","${newDriveLetter}:\Folder" |
set-content $_.fullname
}
Tried to streamline it a little. Too bad you can't just do "get-childitem | get-content -replace | set-content".
get-childitem $path\* -include *.xml, *.config -recurse |
foreach {
(get-content $_) -replace $oldhost,$newhost -replace $oldip,
$newip -replace "${olddriveletter}:\\Folder", "${newDriveLetter}:\Folder" |
set-content $_
}
Upvotes: 1
Reputation:
I suggest to:
## Q:\Test\2019\05\09\SO_56064191.ps1
$oldIP = "192.168.1.2"
$newIP = "192.168.1.3"
$oldhost = "OLDHOSTNAME"
$newhost = "NEWHOSTNAME"
$oldDriveLetter = "C"
$newDriveletter = "E"
$path = '\\{0}\{1}$\Folder' -f $newip,$newdriveletter
ForEach($File in (Get-ChildItem $path\* -Include *.xml,*.config -Recurse)){
(Get-Content $File.FullName -raw) -replace [RegEx]::Escape($oldhost),$newhost `
-replace [RegEx]::Escape($oldip),$newip `
-replace "$olddriveletter(?=:\Folder)",$newDriveLetter |
Set-Content $File.FullName -NoNewline
}
Upvotes: 0