Update Windows Host File Entry Using PowerShell



Let say you want to update the host file particular entry, we have the below host file in our local computer.

Example

Get-Content $env:windir\system32\drivers\etc\hosts

Output

# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#       127.0.0.1       localhost
#       ::1             localhost
8.8.8.8   Google.com

We need to update the google.com entry to IP address 4.4.4.4.

Example

$hostfile = "$env:windir\system32\drivers\etc\hosts"
$file = Get-Content $hostfile
$newfile = $file -replace "8.8.8.8   Google.com","4.4.4.4   Google.com"
Set-Content -Value $newfile -Path $hostfile -Force

Once you check the host file again, a new entry will be displayed.

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

$hostfile = "\RemoteServer\C$\Windows\system32\drivers\etc\hosts"
Updated on: 2021-03-18T07:49:12+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements