Skip to content
David Kittell
David Kittell

Application & System: Development / Integration / Orchestration

  • Services
    • Application Development
    • Online Application Integration
  • Code
  • Online Tools
  • Tech Support
David Kittell

Application & System: Development / Integration / Orchestration

PowerShell – Script for adding/removing/viewing entries to the hosts file.

Posted on March 7, 2019 By David Kittell

As a web developer you often have to use a host file, this script helps assist a safe and fast change with little effort.

#
# Powershell script for adding/removing/showing entries to the hosts file.
#
# Known limitations:
# - does not handle entries with comments afterwards ("<ip>    <host>    # comment")
#
# Original Script: https://gist.github.com/markembling/173887/1824b370be3fe468faceaed5f39b12bad010a417
# Modified Script: https://gist.github.com/andreymir/405b924d32dace51af2b
# Modified Script: https://gist.github.com/lantrix/052dff5737957aae4e25
#

<#
    .SYNOPSIS
        Powershell script for modifying entries in the hosts file.
    .PARAMETER Action
        The action you would like to perform (add, remove, show)
    .PARAMETER HostsFile
        The hosts file to modify
    .PARAMETER IP
        The IP address for the hosts entry
    .PARAMETER Hostname
        The hostname for the entry
    .EXAMPLE
        .\hosts.ps1 -Action add -HostsFile "C:\Windows\System32\drivers\etc\hosts" -IP "127.0.0.1" -Hostname "myserverhost"
    .EXAMPLE
        .\hosts.ps1 add "dkittell.local" "127.0.0.1" "C:\Windows\System32\drivers\etc\hosts"
    .EXAMPLE
        .\hosts.ps1 add "dkittell.local" "127.0.0.1"
    .EXAMPLE
        .\hosts.ps1 -Action remove -HostsFile "C:\Windows\System32\drivers\etc\hosts" -Hostname "myserverhost"
    .EXAMPLE
        .\hosts.ps1 remove "dkittell.local"
    .EXAMPLE
        .\hosts.ps1 -Action show -HostsFile "C:\Windows\System32\drivers\etc\hosts"
    .EXAMPLE
        .\hosts.ps1 show 'C:\WINDOWS\System32\drivers\etc\hosts'
    .EXAMPLE
        .\hosts.ps1 show
#>

param
(
  [Parameter(Mandatory = $true,Position = 0)]
  [ValidateSet("add","remove","show")]
  [string]$Action,

  [Parameter(Position = 1)]
  [string]$Hostname,

  [Parameter(Position = 2)]
  [System.Net.IPAddress]$IP,

  [Parameter(Position = 3)]
  [string]$HostsFile = "$env:SystemRoot" + "\System32\drivers\etc\hosts"

)

#region Functions
function add-host {
<#
.SYNOPSIS
    Powershell function for adding entries to the hosts file.
.PARAMETER HostsFile
    The hosts file to modify
.PARAMETER IP
    The IP address for the hosts entry
.PARAMETER Hostname
    The hostname for the entry
.EXAMPLE
    Add-Host -HostsFile "C:\Windows\System32\drivers\etc\hosts" -IP "127.0.0.1" -Hostname "myserverhost"
#>
  [CmdletBinding()]
  param(
    [Parameter(Mandatory = $true)] [string]$HostsFile,
    [Parameter(Mandatory = $true)] [string]$IP,
    [Parameter(Mandatory = $true)] [string]$Hostname
  )
  remove-host -HostsFile $HostsFile -hostname $Hostname
  $IP + "`t`t" + $Hostname | Out-File -Encoding ASCII -Append $HostsFile
}

function remove-host {
<#
        .SYNOPSIS
        Powershell function for removing entries from a hosts file.
        .DESCRIPTION
        Known limitations: does not handle entries with comments afterwards ("<ip> <host> # comment")
        .PARAMETER HostsFile
        The hosts file to modify
        .PARAMETER Hostname
        The hostname for the entry
        .EXAMPLE
        Remove-Host -HostsFile "C:\Windows\System32\drivers\etc\hosts" -Hostname "myserverhost"
    #>
  [CmdletBinding()]
  param(
    [Parameter(Mandatory = $true)] [string]$HostsFile,
    [Parameter(Mandatory = $true)] [string]$Hostname
  )
  $c = Get-Content $HostsFile
  $newLines = @()

  foreach ($line in $c) {
    $bits = [regex]::Split($line,'\t+')
    if ($bits.count -eq 2) {
      if ($bits[1] -ne $Hostname) {
        $newLines += $line
      }
    } else {
      $newLines += $line
    }
  }

  # Write file
  Clear-Content $HostsFile
  foreach ($line in $newLines) {
    $line | Out-File -Encoding ASCII -Append $HostsFile
  }
}

function Show-Hosts {
<#
        .SYNOPSIS
        Powershell function for showing entries in a hosts file.
        .DESCRIPTION
        Known limitations: does not handle entries with comments afterwards ("<ip> <host> # comment")
        .PARAMETER HostsFile
        The hosts file to access
        .EXAMPLE
        Show-Hosts -HostsFile "C:\Windows\System32\drivers\etc\hosts"
    #>
  [CmdletBinding()]
  param(
    [Parameter(Mandatory = $true)] [string]$HostsFile
  )
  $c = Get-Content $HostsFile
  foreach ($line in $c) {
    $bits = [regex]::Split($line,'\t+')
    if ($bits.count -eq 2) {
      Write-Host $bits[0] `t`t $bits[1]
    }
  }
}

#endregion Functions

#region Take Action
try {
  if ($Action -eq "add") {

    if ($IP -eq '' -or $Hostname -eq '') {
      throw "Not enough arguments for add."
    } else {
      add-host -HostsFile $HostsFile -ip $IP -hostname $Hostname
      Show-Hosts -HostsFile $HostsFile
    }

  } elseif ($Action -eq "remove") {

    if ($Hostname -eq '') {
      throw "Not enough arguments for remove."
    } else {
      remove-host $HostsFile $Hostname
      Show-Hosts -HostsFile $HostsFile
    }

  } elseif ($Action -eq "show") {
    Show-Hosts -HostsFile $HostsFile
  } else {
    throw "Invalid operation '" + $Action + "' - must be one of 'add', 'remove', 'show'."
  }
} catch {
  Write-Host $error[0]
  Write-Host "`nUsage: hosts add <ip> <hostname>`n       hosts remove <hostname>`n       hosts show"
}
#endregion Take Action
<#    
    .EXAMPLE
        .\hosts.ps1 -Action add -HostsFile "C:\Windows\System32\drivers\etc\hosts" -IP "127.0.0.1" -Hostname "myserverhost"
    .EXAMPLE
        .\hosts.ps1 add "dkittell.local" "127.0.0.1" "C:\Windows\System32\drivers\etc\hosts"
    .EXAMPLE
        .\hosts.ps1 add "dkittell.local" "127.0.0.1"
    .EXAMPLE
        .\hosts.ps1 -Action remove -HostsFile "C:\Windows\System32\drivers\etc\hosts" -Hostname "myserverhost"
    .EXAMPLE
        .\hosts.ps1 remove "dkittell.local"
    .EXAMPLE
        .\hosts.ps1 -Action show -HostsFile "C:\Windows\System32\drivers\etc\hosts"
    .EXAMPLE
        .\hosts.ps1 show 'C:\WINDOWS\System32\drivers\etc\hosts'
    .EXAMPLE
        .\hosts.ps1 show
#>

All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.

Related

Code DNS PowerShell

Post navigation

Previous post
Next post

Related Posts

PowerShell – Open URL In Windows Default Browser

Posted on January 2, 2020

As I have found and lost this script from jkdba.com a few times I’m posting it here so I can remember it :) function Invoke-URLInDefaultBrowser { <# .SYNOPSIS Cmdlet to open a URL in the User’s default browser. .DESCRIPTION Cmdlet to open a URL in the User’s default browser. .PARAMETER…

Read More

Display Second Largest Value

Posted on June 26, 2014October 26, 2015

SELECT MAX(col) FROM TABLE WHERE col < ( SELECT MAX(col) FROM TABLE ) Originally Posted on June 26, 2014Last Updated on October 26, 2015 All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it…

Read More

PowerShell – Delete Windows Service

Posted on November 9, 2015

Recently while trying Kentico I had to uninstall it and found that the service didn’t properly uninstall so I found PowerShell was quickly able to remedy that problem. $service = Get-WmiObject -Class Win32_Service -Filter "Name=’KenticoCMSHealthMonitor(Default Web Site_Kentico82)’" $service.delete() $service = Get-WmiObject -Class Win32_Service -Filter "Name=’KenticoCMSScheduler(Default Web Site_Kentico82)’" $service.delete() All information…

Read More

Code

Top Posts & Pages

  • PowerShell - Rename Pictures to Image Taken
  • Front Page
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions

Recent Posts

  • Javascript – Digital Clock with Style
  • BASH – Web Ping Log
  • BASH – Picture / Video File Name Manipulation
  • Mac OSX Terminal – Create SSH Key
  • Bash – Rename Picture

Top Posts

  • PowerShell - Rename Pictures to Image Taken
  • C# - Start/Stop/Restart Services
  • MacPorts / HomeBrew - Rip CD tracks from terminal
  • PowerShell - Show File Extensions
  • Open On Screen Keyboard (OSK)
  • SQLite - Auto-Increment / Auto Generate GUID
©2025 David Kittell | WordPress Theme by SuperbThemes