PoshCode Logo PowerShell Code Repository

Select-Alive (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/70"></script>download | new post

Use as a filter to select computers from a stream on which to act upon later in the pipeline. Example:

get-content servers.txt | select-alive | get-wmiobject win32_foo

No other output will be given unless you set the -Verbose switch or otherwise have enabled $VerbosePreference.

  1. filter Select-Alive {
  2.         param ( [switch]$Verbose )
  3.         trap {
  4.                 Write-Verbose "$(get-date -f 's') ping failed: $computer"
  5.                 continue
  6.         }
  7.         if ($Verbose) {
  8.                 $VerbosePreference = "continue"
  9.                 $ErrorActionPreference = "continue"
  10.         }
  11.         else {
  12.                 $VerbosePreference = "silentlycontinue"
  13.                 $ErrorActionPreference = "silentlycontinue"
  14.         }
  15.         Write-Verbose "$(get-date -f 's') ping start"
  16.         $ping = New-Object System.Net.NetworkInformation.Ping
  17.         $reply = $null
  18.         $_ | foreach-object {
  19.                 $obj = $_
  20.                 # Accomodate different input object types
  21.                 # thx Gaurhoth (http://thepowershellguy.com/blogs/gaurhoth/archive/2007/10/08/an-example-of-how-to-use-new-taskpool.aspx)
  22.                 switch ($obj.psbase.gettype().name) {
  23.                         "DirectoryEntry"    { $cn = $obj.dnshostname[0] }
  24.                         "IPHostEntry"      { $cn = $obj.HostName }
  25.                         "PSCustomObject"    { $cn = $obj.Name }
  26.                         "SearchResult"      { $cn = $obj.properties['dnshostname'][0] }
  27.                         "String"            { $cn = $obj.trim() }
  28.                 }
  29.                 Write-Verbose "$(get-date -f 's') pinging $cn..."
  30.                 $searchCount++
  31.                 $reply = $ping.Send($cn)
  32.                 if ($reply.status -eq "Success") {
  33.                         $cn; $pingCount++
  34.                 }
  35.         }
  36.         Write-Verbose "$(get-date -f 's') ping end - $pingCount/$searchCount online"
  37. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me