PoshCode Archive  Artifact Content

Artifact d1f61a7fda084174c2ce8f52403b8453b45ee1fa1f3e4ae3d2704e95f73db166:

  • File Select-Alive.ps1 — part of check-in [754425eacf] at 2018-06-10 14:06:45 on branch trunk — Selects only objects containing a hostname that is pingable. (user: dragonmc77 size: 1403)

# encoding: ascii
# api: powershell
# title: Select-Alive
# description: Selects only objects containing a hostname that is pingable.
# version: 0.1
# type: function
# author: dragonmc77
# license: CC0
# function: Select-Alive
# x-poshcode-id: 604
# x-archived: 2014-08-01T20:44:26
# x-published: 2009-09-25T13:51:00
#
#
## this filer passes through only objects that are pingable
## it takes any object as input, but the property containing the hostname
## to ping must be specified if the object is not a string
function Select-Alive {param(	[object]$InputObject,
				[string]$Property,
				[int32]$Requests = 3,
				[switch]$Verbose)

	PROCESS {
		if ($InputObject -eq $null) {$In = $_} else {$In = $InputObject}
		if ($In.GetType().Name -eq "String") {
			$HostName = $In
		} 
		elseif (($In | Get-Member | Where-Object {$In.Name -eq $Property}) -ne $null) {
			$HostName = $In.$Property
		} else {return $null}
		
		if ($Verbose) {Write-Host "Pinging $HostName..." -NoNewline}
		for ($i = 1; $i -le $Requests; $i++) {
			$Result = Get-WmiObject -Class Win32_PingStatus -ComputerName . -Filter "Address='$HostName'"
			Start-Sleep -Seconds 1
			if ($Result.StatusCode -ne 0) {
				if ($Verbose) {Write-Host "No response." -ForegroundColor "Red"}
				return $null
			}
		}
		if ($Verbose) {Write-Host "Success." -ForegroundColor "Green"}
		return $In
	}
}