Monday, January 5, 2015

"Ping" in PowerShell style

Hi,

This PowerShell script will retrieve the IP address of a remote computer on the network,
You may provide a list of Hostnames that the script will go through.

# Set Error Action to Silently Continue
# This is in order to continue without any error in case you encounter one
$ErrorActionPreference = "SilentlyContinue"

# Get a list of computers from a TXT file
$list = Get-Content C:\Temp\Hosts.txt


# Create Ping .Net object
$Ping = New-Object System.Net.NetworkInformation.Ping

# Global var to contain all results
$BigResult = `
foreach ($l in $list) {

$Result = "" | Select-Object -Property Hostname, IP

$PingResult = ""
    
    # Try & Catch
    try {
    $PingResult = $Ping.Send($l)
    } 
        catch [System.Net.NetworkInformation.PingException]
        {
            $PingResult = ""
        } # END Try & Catch

# Check the PingResult var for successfull ping
if ($PingResult.Status -eq "Success") {
    
    $Result.IP = $PingResult.Address
    $Result.Hostname = $l

} else {
        
        $Result.IP = "Failed To Retrieve"
        $Result.Hostname = $l

    }

$Result

} # END foreach loop

# Display Output To Screen
$BigResult

# Save Output To CSV File
$BigResult | Export-Csv C:\Temp\IP.csv

Enjoy!