Powershell: Get FQDN Hostname

后端 未结 15 1646
长发绾君心
长发绾君心 2021-01-30 12:24

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}


        
相关标签:
15条回答
  • 2021-01-30 13:10
    [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...

    0 讨论(0)
  • 2021-01-30 13:12

    It can also be retrieved from the registry:

    Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters' |
       % { $_.'NV HostName', $_.'NV Domain' -join '.' }
    
    0 讨论(0)
  • 2021-01-30 13:15

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

    $fqdn= $(ping localhost -n 1)[1].split(" ")[1]
    
    0 讨论(0)
  • 2021-01-30 13:16

    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

    0 讨论(0)
  • 2021-01-30 13:16

    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 讨论(0)
  • 2021-01-30 13:20

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

    0 讨论(0)
提交回复
热议问题