PowerShell for Windows Admins

Oct 26 2011   1:49PM GMT

Remove a host file record

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Next up is removing a record from a hosts file

function remove-hostfilecontent {
 [CmdletBinding()]
 param (
  [parameter(Mandatory=$true)]
  [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")]
  [string]$IPAddress,            

  [parameter(Mandatory=$true)]
  [string]$computer
 )
 $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")            

 $data             

 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.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: