Home > Software design >  Edit hosts file using powershell script
Edit hosts file using powershell script

Time:10-12

I want to create powershell script which gonna detect machine's ip address for example 10.10.10.2 and then looks into hosts file , if there is different ip addresses for example:

10.10.20.5 - test1env.test.loc 10.10.20.6 - test2env.test.loc 10.10.20.7 - test3env.test.loc 10.10.20.8 - test4env.test.loc

then it should replace third column's number with it's current ip address's third column number, it should look like this after script runs:

10.10.10.5 - test1env.test.loc 10.10.10.6 - test2env.test.loc 10.10.10.7 - test3env.test.loc 10.10.10.8 - test4env.test.loc. is it possible to create script which gonna do this?

CodePudding user response:

You can achieve this by reading the file and replacing said entries. It could be easier to replace the whole start of it rather than just a portion. Assuming that the private network could also change to say 172.16 that would make it work even in that case.

To achieve what you want to do you likely need:

  • A way to get the IP (e.g. Powershell get ipv4 address into a variable)
  • A way to read a file (Get-Content)
  • A way to replace a string (e.g. -replace, see about_Comparison_Operators)
  • A way to write that file (Set-Content or Out-File would do)

The pseudo code could look like this:

$ip = findIPs()
$hosts = Get-Content hosts
$oldip = findOldIP($hosts)
$hosts -replace $oldip,$ip | Set-Content hosts
  • Related