I am looking at to see if I can create powershell script to update the contents in the host file.
Anybody know if there are any examples that manipulate the host file using powershell or any other scripting lanaguages?
Thanks.
To update the host file on the remote computer, just change the $hostfile variable location and the rest content will be the same.
To add the content to the host file, we need to first retrieve the content using the Get-Content command and the need to set the content to the host file after adding the entry.
All of these answers are pretty elaborate. This is all you need to add a hosts file entry:
Add-Content -Path $env:windir\System32\drivers\etc\hosts -Value "`n127.0.0.1`tlocalhost" -Force
IP address and hostname are separated by `t which is the PowerShell notation for a tab character.
`n is the PowerShell notation for a newline.
First up, if you're on Vista or Windows 7 make sure you run these commands from an elevated prompt:
# Uncomment lines with localhost on them: $hostsPath = "$env:windir\System32\drivers\etc\hosts" $hosts = get-content $hostsPath $hosts = $hosts | Foreach {if ($_ -match '^\s*#\s*(.*?\d{1,3}.*?localhost.*)') {$matches[1]} else {$_}} $hosts | Out-File $hostsPath -enc ascii # Comment lines with localhost on them: $hosts = get-content $hostsPath $hosts | Foreach {if ($_ -match '^\s*([^#].*?\d{1,3}.*?localhost.*)') {"# " + $matches[1]} else {$_}} | Out-File $hostsPath -enc ascii
Given this I think you can see how to use a regex to manipulate entries as necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With