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).
Why not just export the results to a CSV file?
That’s what filter blocks are for:
$Available | Where {$_.Available} | Format-Table -Auto
Because I plan on passing the output to other scripts that will be executed on computers that are currently on line.
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.
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.