Monthly Archive


Hosts file – add an IPv6 address

This builds on adding an IPv4 address -

function add-IPv6hostfilecontent {            
 param (            
 $file = Join-Path -Path $($env:windir) -ChildPath "system32\drivers\etc\hosts"            
 if (-not (Test-Path -Path $file)){            
   Throw "Hosts file not found"            
 $data = Get-Content -Path $file             
 $data += "$IPAddress  $computer"            
 Set-Content -Value $data -Path $file -Force -Encoding ASCII             


The only difference is that I’ve removed the regex that checks an IPv4 address.  i haven’t been able to figure out a sensible regex for an IPv6 address. if any one wants to post one as a comment I’ll add it to the function with fill credit

The get-hostfilecontent from works with IPv4 and IPv6 addresses

PS> get-hostfilecontent

Server                                       IPAddress                                  
------                                       ---------                                  
RSLAPTOP01                                   fe80:0000:0000:0000:4547:ee51:7aac:521e    

One Response to Hosts file – add an IPv6 address

  • Hi Richard,

    Here’s one version of an IPv6 regex that I intend to publish in a blog post shortly. I also have a proper IPv4 regex that I’ll post for you too 🙂


    $IP4='((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})’ # Match a dotted IPv4 address
    $Hex='[0-9a-f]{1,4}’ # 1-4 hex characters

    # Add ^$ anchors as needed…
    (?x) # Use extended-mode regex (white-space, comments and newlines in the regex definition are ignored)

    (( $Hex :){7} ($Hex |:)) | # 8 Groups of 1-4 Hex characters, or 7 Groups with elided zeroes after 7th group

    (( $Hex :){6} (:$Hex | $IP4 |:)) | # Elided zeroes after 6th Group of 1-4 Hex characters, or 6 Groups followed by dotted IP4
    (( $Hex :){5} (((:$Hex){1,2})| : $IP4 |:)) | # g:g:g:g:g::g g:g:g:g:g::g:g g:g:g:g:g::ip4 g:g:g:g:g::
    (( $Hex :){4} (((:$Hex){1,3})|((:$Hex)? : $IP4 )|:)) | # g:g:g:g::g g:g:g:g::g:g g:g:g:g::g:g:g g:g:g:g::ip4 g:g:g:g::g:ip4 g:g:g:g::
    (( $Hex :){3} (((:$Hex){1,4})|((:$Hex){0,2}: $IP4 )|:)) |
    (( $Hex :){2} (((:$Hex){1,5})|((:$Hex){0,3}: $IP4 )|:)) |
    (( $Hex :){1} (((:$Hex){1,6})|((:$Hex){0,4}: $IP4 )|:)) |

    (:(((: $Hex ){1,7})|((:$Hex){0,5} : $IP4 )|:)) # Elided zeroes at front of address: ::g:g:g:g:g:g:g ::g ::g:ip4 etc
    (%.+)? # Match optional Zone Index (Scope ID) in Link Local address (there may be multiple link-local addresses (e.g. on different adapters) with different zone indexes)


Leave a Reply