Finding Computers with PowerShell Remoting

by Jul 27, 2015

In a previous tip we showed how you can test the network port of a computer. When you have installed the free RSAT tools from Microsoft, you could query your Active Directory and get a list of all computer accounts, or all computer accounts in a given scope (use –SearchBase to limit the search results to a specific OU for example).

Next, you could use the port test to see whether these computers are online and have the PowerShell remoting port 5985 open:

#requires -Version 1 -Modules ActiveDirectory
function Test-Port
{
    Param([string]$ComputerName,$port = 5985,$timeout = 1000)
 
    try
    {
        $tcpclient = New-Object -TypeName system.Net.Sockets.TcpClient
        $iar = $tcpclient.BeginConnect($ComputerName,$port,$null,$null)
        $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
        if(!$wait)
        {
            $tcpclient.Close()
            return $false
        }
        else
        {
            # Close the connection and report the error if there is one
            
            $null = $tcpclient.EndConnect($iar)
            $tcpclient.Close()
            return $true
        }
    }
    catch 
    {
        $false 
    }
}


Get-ADComputer -Filter * | 
Select-Object -ExpandProperty dnsHostName |
ForEach-Object {
    Write-Progress -Activity 'Testing Port' -Status $_
} |
Where-Object -FilterScript {
    Test-Port -ComputerName $_ 
}

Twitter This Tip! ReTweet this Tip!