Set-HostsEntry

Sets a hosts entry in a hosts file.

Syntax

Set-HostsEntry [-IPAddress] <IPAddress> [-HostName] <String> [[-Description] <String>] [[-Path] <String>] [-WhatIf] [-Confirm] [<CommonParameters>]

Description

Sets the IP address for a given hostname. If the hostname doesn't exist in the hosts file, appends a new entry to the end. If the hostname does exist, its IP address gets updated. If you supply a description, it is appended to the line as a comment.

If any duplicate hosts entries are found, they are commented out; Windows uses the first duplicate entry.

This function scans the entire hosts file. If you have a large hosts file, and are updating multiple entries, this function will be slow.

You can operate on a custom hosts file, too. Pass its path with the Path parameter.

Sometimes the system's hosts file is in use and locked when you try to update it. The Set-HostsEntry function tries 10 times to set a hosts entry before giving up and writing an error. It waits a random amount of time (from 0 to 1000 milliseconds) between each attempt.

Parameters

Name Type Description Required? Pipeline Input Default Value
IPAddress IPAddress

The IP address for the hosts entry.

true false
HostName String

The hostname for the hosts entry.

true false
Description String

An optional description of the hosts entry.

false false
Path String

The path to the hosts file where the entry should be set. Defaults to the local computer's hosts file.

false false (Get-PathToHostsFile)
WhatIf SwitchParameter false false
Confirm SwitchParameter false false
CommonParameters This cmdlet supports common parameters. For more information type
Get-Help about_CommonParameters.

EXAMPLE 1

Set-HostsEntry -IPAddress 10.2.3.4 -HostName 'myserver' -Description "myserver's IP address"

If your hosts file contains the following:

127.0.0.1  localhost

After running this command, it will contain the following:

127.0.0.1        localhost
10.2.3.4         myserver   # myserver's IP address

EXAMPLE 2

Set-HostsEntry -IPAddress 10.5.6.7 -HostName 'myserver'

If your hosts file contains the following:

127.0.0.1        localhost
10.2.3.4         myserver   # myserver's IP address

After running this command, it will contain the following:

127.0.0.1        localhost
10.5.6.7         myserver