【问题标题】:How to make PS script show host names as well as the IP如何让 PS 脚本显示主机名和 IP
【发布时间】:2021-11-26 17:55:46
【问题描述】:

这是我用来一次显示多个 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 

【问题讨论】:

  • 嗯,很快,哈哈
  • 这就是我所要做的?谢谢
  • 是的 - 只需在代码块前后的单独行上添加代码围栏(三个连续的反引号):)
  • 任何想法如何解决这个问题?
  • 它只显示 IP 我希望它也可以提取主机名。

标签: powershell scripting ip hostname


【解决方案1】:

在 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

【讨论】:

  • 老兄!太棒了,谢谢
  • 我至少尝试弄清楚将 Resolve-DNS 放在哪里
  • 每次都失败确实设法让它做一些事情,尽管这似乎我在正确的轨道上。
  • @Drone43 只有当你为该网段设置了反向 DNS 时,它才会起作用。如果这是您正在测试的家用路由器的网络,那么您可能不会有太多运气。
  • @Drone43 如果我的回答解决了您的问题,请考虑通过单击左侧的复选标记将其标记为“已接受”。如果您自己找到了不同的解决方案,请更新您发布的答案,详细说明解决方案是什么 :)
猜你喜欢
  • 1970-01-01
  • 2020-09-22
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多