输出正确的IP

时间:2018-04-11 21:59:40

标签: powershell ip output customization ping

现在,以下脚本从CSV文件导入信息,然后在CSV文件中输出计算机名称,expectedIP,Status,GoodIP,dnsName。这都是通过自定义PS对象。

我目前正在尝试将输出称为实际IP。我不太确定如何通过ping主机名的ping功能来拉取IP。例如,如果要ping的主机名检查IP并返回true或false。它怎么能输出服务器的实际IP而不是输出真或假?

这是脚本:

$compinfo = import-csv .\compinfo.csv

$lookupData = foreach ($comp in $cominfo) {
    $nslkup = [System.Net.DNS]::GetHostEntry($comp.hname)
    $ping = (Test-Connection -ComputerName $comp.hname -Count 1 -ErrorAction SilentlyContinue)
    if ($ping) {
        $status = "up"
    } else {
        $status = "down"
    }
    if ($nslkup.AddressList.IPAddressToString -eq $comp.ip) {
        $ipgood = $true
    } else {
        $ipgood = $false
    }
    [PSCustomObject]@{
        computerName = $comp.hname
        expectedIp   = $comp.ip
        status       = $status
        goodIp       = $ipgood
        dnsName      = $nslkup.hostname
    }
}

$lookupData | Export-Csv .\lookups.csv -NoTypeInformation

1 个答案:

答案 0 :(得分:0)

感谢对此发表评论的所有人。我想到了。以下是将来遇到此问题的其他任何人的正确代码。

$compinfo = import-csv .\compinfo.csv

$lookupData = foreach($comp in $compinfo)
{
    $nslkup = [System.Net.DNS]::GetHostEntry($comp.hname)
    $ping = (Test-Connection -ComputerName $comp.hname -Count 1 -ErrorAction SilentlyContinue)
    if($ping)
    {
        $status = "up"
    }
    else
    {
        $status = "down"
    }
    if($nslkup.AddressList.IPAddressToString -eq $comp.ip)
    {
        $ipgood = $true
    }
    else
    {
        $ipgood = $nslkup.AddressList.IPAddressToString
    }
    [pscustomobject]@{
        computerName = $comp.hname
        expectedIp = $comp.ip
        status = $status
        goodIp = $ipgood
        dnsName = $nslkup.hostname
    }
} 

$lookupData | export-csv .\lookups.csv -NoTypeInformation

注意我用$ nslkup.AddressList.IPAddressToString

替换了$ False