Q:

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.

A:

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.

A:

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

A:

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

