Archive

Posts Tagged ‘sysadmin’

Ping Multiple Hosts with PowerShell and Return Useful Information

September 4, 2012 4 comments

A lot of our time in IT is spent making sure systems are up and running. Most times our first test when troubleshooting an issue is to perform a PING command. For that reason I have created the script below which in essence just performs the Test-Connection cmdlet. This script only provides me the useful information that I want from the cmdlet, both onscreen and in a csv file.

If you want to get really fancy you could perform a get-qadcomputer command and pipe the output to a CSV file. Then use that CSV file as the input file for the script below. If you did this you would be able to know which machines in your domain can respond to a PING response.


###########################################################################
#
# NAME: Ping-Host.ps1
#
# AUTHOR: Joshua Schofield
#
# COMMENT: If using a CSV file, you must have a column named DNSName in order for script to complete.
#
# EXAMPLE: c:\scripts\ping-host.ps1 -sourcefile c:\scripts\csv\servers.csv -oufile c:\scripts\logs\logfile.csv
#
# VERSION HISTORY: 1
#
# VERSION DATE:    8/21/2012
#
# VERSION COMMENTS: Tested and Validated
#
#
###########################################################################

param (

	[Parameter(Mandatory = $true)]
	$SourceFile,

	[Parameter(Mandatory = $true)]
	$OutFile

)

Function Ping-Hosts {

param ($server)

$test = Test-Connection $server -Count 1 -Quiet -ErrorAction SilentlyContinue
$ip = Test-Connection $server -Count 1 | select ipv4address -ErrorAction SilentlyContinue
$ip = $ip.IPV4Address

if ($test.ToString() -like "true") {

	Write-Host "$server $ip is pingable" -ForegroundColor green
	Write-Output "$server,$ip,yes" | Out-File $OutFile -Append

}
else {
	Write-Host "$server not pingable" -ForegroundColor Red
	Write-Output "$server,$ip,no" | Out-File $OutFile -Append

}

$test = $null
$name = $null
$server = $null
$ip = $null
}

$filetype = $SourceFile.split(".")[1]

Write-Output "ServerName,IP,RespondsToPING" | Out-File $OutFile -force

if ($filetype -eq "txt"){

	gc $sourcefile | % {

		ping-hosts $_

}
}

Elseif ($filetype -eq "csv"){

	Import-Csv $sourcefile | % {

		ping-hosts $_.dnsname

}
}

else{

Write-Host "Filetype: $filetype not recognized. Filetype must be .csv or .txt . Please try again." -ForegroundColor DarkRed -BackgroundColor White

}

Advertisements
%d bloggers like this: