I remember when I first discovered the mail merge feature… it amazed the twelve-year-old me that I could write a letter once, and then AppleWorks would address that letter to the several hundred people in my database. I was thrilled with it.
Last week, I was working with a client who moved a server. No big deal, right? Well unfortunately, this was a server that collected information from every other server in the environment… several hundred of them, to be precise. If the collection application were programmed differently, there would have been an option to send out to all of the servers the changed IP address. This application did not work that way. Even though we have an agent deployed to every server, there was no automated way to make the change on the agent side… at least, not out of the box.
It turns out that the information we needed to change was in a file I will call ‘c:\Program Files\Collector\agent.conf.’ The file consisted of three lines:
[Collector Agent Settings]
Collector Hostname: servername.domain.com
Collector IP Address: 10.201.15.72
While the collector hostname was not changing, the IP address had to, because it had been relocated to a different datacenter. The new address was going to be 10.205.119.70. (Obviously none of these addresses are the actual addresses from my client… don’t go looking for them!) I had to change the IP address in this file… but I had to do it across about 600 servers. Fortunately I have my deployment tool that allows me to send the script to every server… and I have PowerShell, which let me build the following script:
$s1 = 10.201.15.72
$s2 = 10.205.119.70
$file =”c:\Program Files\Collector\agent.conf”
# Stop the service
net stop Collector
# Make my change
(Set-Content -path $file) -replace $s1, $s2
# Restart the service
net start Collector
First I set my variables, which are the original IP address, the new IP address, and the file name.
Next I stop the service, because while the service is actually running, the configuration file is protected. In some cases, you may also have a Process protecting it, so you would then have to add a Kill command.
The Set-Content command does the following:
- Selects the file (from the variable)
- Replaces the first variable with the second variable.
And lastly, I restart the service.
Now, I used this script for a configuration file, but there is no reason it cannot be used for any other purpose. Changing text in ASCII files is something you might need to do on a regular basis. Scripting it will save you a lot of time and effort.