83

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.

1
  • 1
    instead of using invoke-command, you can do: $server = (hostname)
    – x0n
    Sep 4, 2012 at 22:47

18 Answers 18

123

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.
4
  • 1
    This is the correct way to get this information when running automation scripts. The $env:userdnsdomain returns NULL unless a user is logged in.
    – BFoust
    May 16, 2013 at 18:30
  • 5
    [System.Net.Dns]::GetHostByName(($env:computerName)).HostName Jan 29, 2015 at 11:09
  • 1
    Looks like GetHostByName is deprecated, and the suggested method is to use GetHostEntry instead. i.e. [System.Net.Dns]::GetHostEntry($Env:ComputerName).HostName
    – deadlydog
    May 4, 2021 at 17:29
  • 1
    This does not work anyways. If you have an alternate domain name pointing to the machine that is not the AD FQDN, it will happily return that.
    – Pxtl
    Aug 4, 2022 at 21:24
89

How about: "$env:computername.$env:userdnsdomain"

This actually only works if the user is logged into a domain (i.e. no local accounts), logged into the same domain as the server, and doesn't work with disjointed name space AD configurations.

Use this as referenced in another answer:

$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain ; Write-Host $myFQDN
5
  • Hmm...so what does it mean to get the fully qualified domain name of a computer that isn't ON a domain? What do your answer output? Just the machine name? Your're saying my answer doesn't show your machine name even?
    – aquinas
    Sep 4, 2012 at 18:30
  • 2
    We have two domains so this won't work. This method assumes the domain the PS script is running on, which may not be the case. Feb 25, 2014 at 23:56
  • not working in powershell for me, better to go with answer posted by perilbrain
    – Ranvir
    Sep 16, 2014 at 9:42
  • 3
    This fails if the user logged in is in a different domain from the computer. It pulls the user's domain information, not the machine's
    – Daniel
    Aug 6, 2015 at 22:50
  • A shorter version of the same is $myFQDN = Get-WmiObject win32_computersystem | %{ $_.DNSHostName + "." + $_.Domain} Jan 13, 2023 at 11:41
34

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

1
  • 1
    Nicely done. The [string] casts aren't necessary. A variant of the WMI command (updated for CIM) that only requires one call: Get-CimInstance win32_computersystem | % { $_.Name + '.' + $_.Domain }
    – mklement0
    Feb 10, 2018 at 18:49
12

This worked in PS and PS Core on Windows (Tested on Versions 5.1 and 7.2)

[System.Net.Dns]::Resolve($null).HostName
0
9
[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...

4

It can also be retrieved from the registry:

Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters' |
   % { $_.'NV HostName', $_.'NV Domain' -join '.' }
3
(Get-ADComputer $(hostname)).DNSHostName
2
  • 1
    The provided answer was flagged for review as a Low Quality Post. Here are some guidelines for How do I write a good answer?. This provided answer may be correct, but it could benefit from an explanation. Code only answers are not considered "good" answers. From review. Sep 17, 2019 at 7:14
  • I never understand the point to explain a single command. This is so picky. I guess its a robotic response?
    – Carsten
    Aug 23, 2023 at 7:03
3

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

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

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.

2

A cleaner format FQDN remotely

[System.Net.Dns]::GetHostByName('remotehost').HostName
2
  • replace remotehost (leave the tics) with the hostname looked for and you will get FQDN: [System.Net.Dns]::GetHostByName('lookedforserver').HostName Jun 8, 2022 at 18:46
  • [System.Net.Dns]::GetHostByName('localhost').HostName Jun 8, 2022 at 18:50
1

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...

1

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
1

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()
0
0

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(".")
0

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
2
  • this works for dns alias as well as "deep" domain names.. eg server01.us.fred.com with C-Name MyAppServer .. you can set $forname to "MyAppServer" and get shortname as well as domain name
    – CBB
    Mar 1, 2018 at 15:51
  • Consider to delete it while editing and when ready you undelete... like this I'm hovering the dv and flag dialog. Mar 1, 2018 at 16:35
0

Using Resolve-DNSName command this way works for PowerShell 5.1 and 7.3 in my case.

(Resolve-DnsName -Name 'hostname').Name

Supporting Resource

  • Resolve-DNSName

    Description

    The Resolve-DnsName cmdlet performs a DNS query for the specified name. This cmdlet is functionally similar to the nslookup tool which allows users to query for names.

0

The ADSystemInfo object can retrieve the DNS name of the local computer's domain:

$env:COMPUTERNAME + '.' + [System.__ComObject].InvokeMember("DomainDnsName", [System.Reflection.BindingFlags]::GetProperty, $null, (New-Object -ComObject "ADSystemInfo"), $null)

https://learn.microsoft.com/en-us/windows/win32/adsi/iadsadsysteminfo-property-methods

-2
"$env:computername.$env:userdnsdomain" 

will work if separated out like this

"$env:computername"+"$env:userdnsdomain"
2
  • This is unfortunately not accurate, as the user logon domain is not guaranteed to be the the same as the server domain, especially in a production environment, where the users can be declared in domain example.net but the servers be in siteA.example.net, siteB.example.net, corp.example.net, etc.
    – Thomas BDX
    May 2, 2016 at 20:42
  • the $env:USERdnsdomain might also be empty if you run the script under a local user (like NTAUTHOITY\LOCAL_SERVICE) May 27, 2016 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.