How to update the windows host file entry using PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

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


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


# For example:
#          # source server
#              # x client host

# localhost name resolution is handled within DNS itself.
#       localhost
#       ::1             localhost

We need to update the entry to IP address


$hostfile = "$env:windir\system32\drivers\etc\hosts"
$file = Get-Content $hostfile
$newfile = $file -replace "",""
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"
Published on 18-Mar-2021 12:17:53