PoshCode Archive  Artifact [909e6dec38]

Artifact 909e6dec38f93edc8e0d5c0fc40b2c93d0b47fefc81fe4476b12ceffbfd75680:

  • File Select-Alive.ps1 — part of check-in [2725f4c2a6] at 2018-06-10 14:22:47 on branch trunk — Use as a filter to select computers from a stream on which to act upon later in the pipeline. Example: (user: unknown size: 1672)

# encoding: ascii
# api: powershell
# title: Select-Alive
# description: Use as a filter to select computers from a stream on which to act upon later in the pipeline. Example:
# version: 0.1
# license: CC0
# x-poshcode-id: 70
# x-archived: 2008-11-20T11:55:10
#
# 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.
#
filter Select-Alive {
	param ( [switch]$Verbose )
	trap {
		Write-Verbose "$(get-date -f 's') ping failed: $computer"
		continue
	}
	if ($Verbose) {
		$VerbosePreference = "continue"
		$ErrorActionPreference = "continue"
	}
	else {
		$VerbosePreference = "silentlycontinue"
		$ErrorActionPreference = "silentlycontinue"
	}
	Write-Verbose "$(get-date -f 's') ping start"
	$ping = New-Object System.Net.NetworkInformation.Ping
	$reply = $null
	$_ | foreach-object {
		$obj = $_
		# Accomodate different input object types
		# thx Gaurhoth (http://thepowershellguy.com/blogs/gaurhoth/archive/2007/10/08/an-example-of-how-to-use-new-taskpool.aspx)
		switch ($obj.psbase.gettype().name) {
			"DirectoryEntry"    { $cn = $obj.dnshostname[0] }
			"IPHostEntry"		{ $cn = $obj.HostName }
			"PSCustomObject"    { $cn = $obj.Name }
			"SearchResult"      { $cn = $obj.properties['dnshostname'][0] }
			"String"            { $cn = $obj.trim() }
		}
		Write-Verbose "$(get-date -f 's') pinging $cn..."
		$searchCount++
		$reply = $ping.Send($cn)
		if ($reply.status -eq "Success") {
			$cn; $pingCount++
		}
	}
	Write-Verbose "$(get-date -f 's') ping end - $pingCount/$searchCount online"
}