【问题标题】:Powershell : Get remote computer namePowershell:获取远程计算机名称
【发布时间】:2019-12-31 03:48:45
【问题描述】:

我知道要获取计算机名称,我们可以访问该服务器并通过 cmd 执行此命令。

但是是否可以通过 ip 地址获取远程计算机名称?所有这些ip地址都是内部ip。

【问题讨论】:

标签: powershell


【解决方案1】:

这不是 PowerShell 特定的问题或限制。这是一个非常常见的网络管理员要做的事情。

正如 BACON 所述,您可以使用 nslookup,但 Windows 也提供 .Net 命名空间,而 PowerShell 为该用例提供 DNS cmdlet。

在 Stackoverflow 上也被多次询问和回答。在 MS 文档站点、TechNet、MSDN 和其他博客上,这是一个非常有据可查的内容。例如

Powershell : Resolve Hostname from IP address and vice versa

# Find machine name from IP address:

$ipAddress= "192.168.1.54"
[System.Net.Dns]::GetHostByAddress($ipAddress).Hostname
Resolve Hostname to IP Address:
$machineName= "DC1"
$hostEntry= [System.Net.Dns]::GetHostByName($machineName)
$hostEntry.AddressList[0].IPAddressToString



<#
Resolve Hostname for set of IP addresses from text file:

Use the below powershell script to find machine name for multiple IP addresses. 
First create the text file ip-addresses.txt which includes one IP address in 
each line. You will get the machinename list in the txt file machinenames.txt.
#>

Get-Content C:\ip-addresses.txt | 
ForEach-Object{
    $hostname = ([System.Net.Dns]::GetHostByAddress($_)).Hostname
    if($? -eq $True) {
      $_ +": "+ $hostname >> "C:\machinenames.txt"
    }
    else {
       $_ +": Cannot resolve hostname" >> "C:\machinenames.txt"
    }
}


<#
Find Computer name for set of IP addresses from CSV:
Use the below powershell script to get hostname for multiple IP addresses from 
csv file. First create the csv file ip-addresses.csv which includes the column 
IPAddress in the csv file. You will get the hostname and IP address list in the 
csv file machinenames.csv.
#>

Import-Csv C:\ip-Addresses.csv | 
ForEach-Object{
    $hostname = ([System.Net.Dns]::GetHostByAddress($_.IPAddress)).Hostname

    if($? -eq $False){
    $hostname="Cannot resolve hostname"
    }

    New-Object -TypeName PSObject -Property @{
          IPAddress = $_.IPAddress
          HostName = $hostname
    }
} | 
Export-Csv 'D:\Temp\machinenames.csv' -NoTypeInformation -Encoding UTF8

【讨论】:

    【解决方案2】:

    还有一个非常简单的cmdlet Resolve-DnsName

    Resolve-DnsName 10.1.1.1
    

    结果有很多细节。 NameHost 就是你想要的:

    Name                           Type   TTL   Section    NameHost
    ----                           ----   ---   -------    --------
    1.1.1.10.in-addr.arpa          PTR    3600  Answer     ServerName.DomainName.com
    

    【讨论】:

      猜你喜欢
      • 2021-10-31
      • 2017-01-01
      • 2022-10-17
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多