Filter Boolean true results

This topic contains 5 replies, has 4 voices, and was last updated by Profile photo of Graham Beer Graham Beer 6 months ago.

  • Author
    Posts
  • #41233
    Profile photo of Chris Ediger
    Chris Ediger
    Participant

    I've got a script that tests to see which computers from AD are online at this time:

    param (
    $pattern
    )
    $computers = Get-ADComputer -filter {name -like $pattern} | Select-Object -ExpandProperty Name
    $available = ForEach($computer in $computers)
    {
    $ping = Test-Connection -ComputerName $computer -Count 1 -Quiet
    [PSCustomObject]@{
    Hostname = $computer
    Available = $ping }
    }
    $available | Sort-Object Available | Format-Table -AutoSize

    It returns the hostname and true if on line and false if not. I want to filter out the hosts that are returned false (not online).

  • #41249
    Profile photo of Wilfredo Perez
    Wilfredo Perez
    Participant

    Why not just export the results to a CSV file?

    • #41256
      Profile photo of Chris Ediger
      Chris Ediger
      Participant

      Because I plan on passing the output to other scripts that will be executed on computers that are currently on line.

  • #41254
    Profile photo of David Johnson
    David Johnson
    Participant

    That's what filter blocks are for:

    $Available | Where {$_.Available} | Format-Table -Auto

  • #41270
    Profile photo of Chris Ediger
    Chris Ediger
    Participant

    Got it figured out:

    param (
    $pattern
    )

    $computers = Get-ADComputer -filter {name -like $pattern} |
    Select-Object -ExpandProperty Name

    ForEach($computer in $computers)
    {
    [bool]$ping = Test-Connection -ComputerName $computer -Count 1 -Quiet
    if ($ping)
    {
    $computer
    }
    }

    The parameter takes a name pattern you want to run the script on. For example I have a group of computers whose names are UKOFCLT01, UKOFCLT02, UKOFCLT03 etc... so I'd enter UKOFCLT* to test all names in that office for connectivity.

  • #41377
    Profile photo of Graham Beer
    Graham Beer
    Participant

    In this line, "[bool]$ping = Test-Connection -ComputerName $computer -Count 1 -Quiet", you do not need the [bool] type as -quiet on test-connection will give a true or false result.

    I.e.
    PS C:\WINDOWS\system32> test-connection localhost -Quiet
    True

    I've re-written your code a little:

    $Computers = Get-Content 'C:\temp\Computers.txt'
    
    $Computers | 
        foreach { if (Test-Connection -ComputerName $_ -count 1 -Quiet) { 
            "$_ is Online"
        }else{
            "$_ is offline"} 
             }
    Output:
    localhost is Online
    testbox is offline
            
    

    I've used get content as a test, but you can add your get-adcomputer line here. Also, where I have 'online' and 'offline', add what output you require. Hope that helps Chris.

You must be logged in to reply to this topic.