[windows] Powershell: Get FQDN Hostname

I want to retrieve the FQDN name of windows server via powershell script. I have found 2 solution so far:

$server =  Invoke-Command -ScriptBlock {hostname}

Above line will print just the short name of the server

$sysinfo = Get-WmiObject -Class Win32_ComputerSystem
$server = “{0}.{1}” -f $sysinfo.Name, $sysinfo.Domain

Above two line will get me the FQDN but this looks really nasty code to retrieve just the hostname :(

So, My question is, is there an easier way to get the FQDN in powershell. I am a bash/perl coder and recently picked up powershell.. so finding it difficult.

Thanks.

This question is related to windows powershell

The answer is


Here is a way to determine the FQDN of a server based on the "Name" and "DistinguishedName". Works for multiple domains:

$server = Get-ADComputer serverName -Server domainName -Properties * | select Name, DistinguishedName
$domain = $server.DistinguishedName -split ","
$domain = $domain | ? {$_ -like 'DC=*'}
$domain = $domain -join "."
$domain = $domain -replace "DC="
$FQDN = $server.Name + "." + $domain

Here's the method that I've always used:

$fqdn= $(ping localhost -n 1)[1].split(" ")[1]

To get FQDN of local computer:

[System.Net.Dns]::GetHostByName($env:computerName)

or

[System.Net.Dns]::GetHostByName($env:computerName).HostName

To get FQDN of Remote computer:

[System.Net.Dns]::GetHostByName('mytestpc1')

or

For better formatted value use:

[System.Net.Dns]::GetHostByName('mytestpc1').HostName
  • For remote machines make sure host is reachable.

[System.Net.Dns]::GetHostByName((hostname)).HostName

$env:computerName returns NetBIOS name of the host, so that both previous examples return netbioshostname.domainsuffix (not FQDN!) instead of dnshostname.domainsuffix (FQDN)

for example, host has FQDN aa-w2k12sv-storage.something.com and NetBIOS name aa-w2k12sv-stor (an easy case, I usually change NetBIOS name)

the hostname utility returns dnshostname, i.e., the first part of FQDN and code

[System.Net.Dns]::GetHostByName((hostname)).HostName

returns the right FQDN

Comment: never use the same NetBIOS and DNS names of AD domains and hosts. If your or 3rd party application writes to the log: "cannot connect to hostname.domainsuffix", what name it tries to resolve? If you see in the log "cannot connect to netbiosname.domainsuffix", no doubt, a lazy programmer added domain suffix to the NetBIOS name and you are sure, this is a bug, and can open a ticket to force them to fix the issue...


"$env:computername.$env:userdnsdomain" 

will work if separated out like this

"$env:computername"+"$env:userdnsdomain"

to get the fqdn corresponding to the first IpAddress, it took this command:

PS C:\Windows\system32> [System.Net.Dns]::GetHostByAddress([System.Net.Dns]::GetHostByName($env:computerName).AddressList[0]).HostName
WIN-1234567890.fritz.box

where [System.Net.Dns]::GetHostByName($env:computerName).AddressList[0] represents the first IpAddress-Object and [System.Net.Dns]::GetHostByAddress gets the dns-object out of it.

If I took the winning solution on my standalone Windows, I got only:

PS C:\Windows\system32> (Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain
WIN-1234567890.WORKGROUP

that's not what I wanted.


(Get-ADComputer $(hostname)).DNSHostName

A cleaner format FQDN remotely

[System.Net.Dns]::GetHostByName('remotehost').HostName

I use the following syntax :

$Domain=[System.Net.Dns]::GetHostByName($VM).Hostname.split('.')
$Domain=$Domain[1]+'.'+$Domain[2]

it does not matter if the $VM is up or down...


How about this

$FQDN=[System.Net.Dns]::GetHostByName($VM).Hostname.Split('.')
[int]$i = 1
[int]$x = 0
[string]$Domain = $null
do {
    $x = $i-$FQDN.Count
    $Domain = $Domain+$FQDN[$x]+"."
    $i = $i + 1
} until ( $i -eq $FQDN.Count )
$Domain = $Domain.TrimEnd(".")

Local Computer FQDN via dotNet class

[System.Net.Dns]::GetHostEntry([string]$env:computername).HostName

or

[System.Net.Dns]::GetHostEntry([string]"localhost").HostName

Reference:

Dns Methods (System.Net)

note: GetHostByName method is obsolete


Local computer FQDN via WMI query

$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain
Write-Host $myFQDN

Reference:

Win32_ComputerSystem class


I have the following add.. I need to separate out the dns suffix from the hostname.. and I only "know" the servers alias shortname... and want to know what the dns suffix is

#example:
#serveralias:     MyAppServer.us.fred.com
#actualhostname:  server01.us.fred.com 
#I "know":        "MyAppServer" .. I pass this on as an env var called myjumpbox .. this could also be $env:computername


$forname                 = $env:myjumpbox
$fqdn                    = [System.Net.Dns]::GetHostByName($forname).Hostname
$shortname               = $fqdn.split('.')[0]
$domainname              = $fqdn -split $fqdn.split('.')[0]+"."
$dnssuf                  = $domainname[1]  
" name parts are- alias: " + $forname + " actual hostname: " + $shortname + " suffix: " + $dnssuf

#returns

name parts are- alias: MyAppServer actual hostname: server01 suffix: us.fred.com

If you have more than one network adapter and more than one adapter is active (f.e WLAN + VPN) you need a bit more complex check. You can use this one-liner:

[System.Net.DNS]::GetHostByAddress(([System.Net.DNS]::GetHostAddresses([System.Environment]::MachineName) | Where-Object { $_.AddressFamily -eq "InterNetwork" } | Select-Object IPAddressToString)[0].IPAddressToString).HostName.ToLower()

It can also be retrieved from the registry:

Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters' |
   % { $_.'NV HostName', $_.'NV Domain' -join '.' }