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

Time:10-07

This is the code I'm using to show mutiple IP addresses in one sitting.

I want the code to be able to show Host names as well with the same results of this code.

It will tell you if the IP is up or if it's down. ( running or not running). I'm not sharp with Powershell scripting but i'm learning slowly. Any help would be greatly appreciated.

$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 

CodePudding user response:

On Windows you can use the Resolve-DnsName cmdlet to perform a reverse DNS lookup for the IP:

# 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
  • Related