How to add the entry in the windows host file using PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

To add the content to the host file, we need to first retrieve the content using the Get-Content command and the need to set the content to the host file after adding the entry. The Code is shown below. We need to add the global entry to it.

Example

$file = "C:\Windows\System32\drivers\etc\hosts"
$hostfile = Get-Content $file
$hostfile += "8.8.8.8   Google.com"
Set-Content -Path $file -Value $hostfile -Force

Once you check the host file entry  "8.8.8.8          Google.com" will be added to the host file.

To add the entry on the remote computer, you just need to point that file location to the host file of the remote server and the rest of the content will be the same.

Example

$file = \\Comptuter1\C$\Windows\System32\drivers\etc\hosts
$hostfile = Get-Content $file
$hostfile += "8.8.8.8   Google.com"
Set-Content -Path $file -Value $hostfile -Force
raja
Published on 18-Mar-2021 07:45:05
Advertisements