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_fooNo 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"
- $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"
- }
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.
PowerShell Code Repository