如何让 PS 脚本显示主机名和 IP

How to make PS script show host names as well as the IP

这是我用来一次显示多个 IP 地址的代码。

我希望代码能够显示主机名以及与此代码相同的结果。

它会告诉您 IP 是可用还是已关闭。 (运行 或不 运行)。我对 Powershell 脚本不熟悉,但我学得很慢。任何帮助将不胜感激。

$names = Get-Content "C:\Users\jason.darby\Desktop\useful scripts\ip.txt"
foreach ($name in $names) {
    if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue) {
        Write-Host "$name is UP" -ForegroundColor Green
        $Output += "$name is UP" + "`n"
    }
    else {
        Write-Host "$name is DOWN" -ForegroundColor Red
        $Output += "$name is DOWN" + "`n"
    }
}
Start-Sleep -s 10 

在 Windows 上,您可以使用 the Resolve-DnsName cmdlet 对 IP 执行反向 DNS 查找:

# read ip addresses from file
$IPs = Get-Content "C:\Users\jason.darby\Desktop\useful scripts\ip.txt"

# let's collect the output in an array instead of a string
$output = @()

foreach ($IPAddress in $IPs) {
    # Resolve host name via reverse dns
    $hostname = try {
        (Resolve-DnsName $IPAddress -Type PTR -QuickTimeout).NameHost
    } catch {
        # Output "UNKNOWN" if the name resolution fails
        'UNKNOWN'
    }

    # ping the IP address
    if (Test-Connection -ComputerName $IPAddress -Count 1 -ErrorAction SilentlyContinue) {
        $status = "$IPAddress [$hostname] is UP"
        Write-Host $status -ForegroundColor Green
    }
    else {
        $status = "$IPAddress [$hostname] is DOWN"
        Write-Host $status -ForegroundColor Red
    }

    # Collect status message to output array
    $Output += $status
}
Start-Sleep -s 10