header image

Remove a host file record

Posted by: | October 26, 2011 | No Comment |

Next up is removing a record from a hosts file

function remove-hostfilecontent {            
 param (            
 $file = Join-Path -Path $($env:windir) -ChildPath "system32\drivers\etc\hosts"            
 if (-not (Test-Path -Path $file)){            
   Throw "Hosts file not found"            
 Write-Verbose "Remove IP Address"            
 $data = ((Get-Content -Path $file) -notmatch "$ip\s+$computer")            
 Set-Content -Value $data -Path $file -Force -Encoding ASCII             


Get an IP Address and computer as before. Create the path to the hosts file.

Read the files contents and perform a –notmatch using the IP Address and computername in the regular expression.  \s+ means one or more white spaces. This removes the record we don’t want.

I managed to create a regular expression that works Smile

Then write the data back.  normally I wouldn’t look at completely re-writing a file like this but the hosts file is small so its probably as quick and it makes the code really simple.

under: Networking, PowerShellV2