tags:

views:

126

answers:

1

Hello,

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.

+1  A: 

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 {$_}}
$hosts | Out-File $hostsPath -enc ascii

Given this I think you can see how to use a regex to manipulate entries as necessary.

Keith Hill