Set-HostEntry

Topics: Archive - Toolkit Extensions
Apr 30, 2014 at 4:56 PM
Something else I find useful. While using HOST Entries is typically bad form I have found several reason's I need to do it and this is a great piece to have in my toolkit extensions.
function Set-HostEntry{

    <#
        .DESCRIPTION
            This function checks to see if an entry exists in the hosts file.
            If it does not, it attempts to add it and verifies the entry.

        .EXAMPLE
            Set-HostEntry -IPAddress 192.168.0.1 -HostName MyMachine

        .EXTERNALHELP
            None.

        .FORWARDHELPTARGETNAME
            None.

        .INPUTS
            System.String.

        .LINK
            None.

        .NOTES
            None.

        .OUTPUTS
            System.String.

        .PARAMETER IPAddress
            A string representing an IP address.

        .PARAMETER HostName
            A string representing a host name.

        .SYNOPSIS
            Add entries to the hosts file.
    #>

  param(
    [parameter(Mandatory=$true,position=0)]
    [string]
    $IPAddress,
    [parameter(Mandatory=$true,position=1)]
    [string]
    $HostName
  )

    $HostsLocation = "$env:windir\System32\drivers\etc\hosts";
    $NewHostEntry = "`t$IPAddress`t$HostName";

    if((gc $HostsLocation) -contains $NewHostEntry)
    {
      Write-Log -Text "The hosts file already contains the entry: $NewHostEntry.  File not updated.";
    }
    else
    {
    Write-Log -Text "The hosts file does not contain the entry: $NewHostEntry.  Attempting to update.";
        Add-Content -Path $HostsLocation -Value $NewHostEntry;
    }

    # Validate entry
    if((gc $HostsLocation) -contains $NewHostEntry)
    {
      Write-Log -Text "$NewHostEntry, added to $HostsLocation.";
    }
    else
    {
    Write-Log -Text "The new entry, $NewHostEntry, was not added to $HostsLocation.";
    }
}
Coordinator
Apr 30, 2014 at 5:01 PM
Nice!
Coordinator
Apr 30, 2014 at 5:10 PM
Good work, thanks for sharing!