Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell to manipulate host file

Tags:

powershell

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.

like image 537
Tony Avatar asked Apr 08 '10 18:04

Tony


People also ask

How do I change the hosts file in PowerShell?

To update the host file on the remote computer, just change the $hostfile variable location and the rest content will be the same.

How do I add a host to PowerShell?

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.


2 Answers

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.

like image 58
sherenator Avatar answered Oct 05 '22 06:10

sherenator


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.

like image 35
Keith Hill Avatar answered Oct 05 '22 06:10

Keith Hill