Okay, I teased yesterday… so check out this function:
Function Ping-Name {
PROCESS {
$wmi = get-wmiobject -query “SELECT * FROM Win32_PingStatus WHERE Address = ‘$_'”
if ($wmi.StatusCode -eq 0) {
$_
}
}
}
Notice that the function name looks like a cmdlet name? This function can sorta be used l ike a cmdlet. For example:
Get-Content c:\computers.txt | Ping-Name
This will retrieve the contents of c:\computers.txt, which I’m pretending is a text file with one computer name or IP address per line. The collection of lines is piped to my Ping-Name function, which pings each. The upshot is that only the computers which were pingable will come out the other end – those could, in turn, be piped to some other cmdlet which was connecting to remote computers.
This is a short, yet sweet, example of how PowerShell functions can really extend your PowerShell environment with new functionality. It also demonstrates a filtering function, one which takes “x” number of objects in an input collection, but only outputs those objects which meet some criteria (in this case, the ability to be pinged). It also demonstrates how to easily work with pipeline collections via a PROCESS Scriptblock, and how to output one object at a time from the function – just by outputting the $_ object itself – with the end result of the function outputting a collection of those individual objects.
Have a great weekend, folks!