Scanning Ports

by Jan 10, 2019

Here is a straightforward way to test ports on a local or remote system. You can even specify a timeout (in milliseconds):

function Get-PortInfo
{
    param
    (
        [Parameter(Mandatory)]
        [Int]
        $Port,
    
        [Parameter(Mandatory)]
        [Int]
        $TimeoutMilliseconds,
        
        [String]
        $ComputerName = $env:COMPUTERNAME
    )
  
    # try and establish a connection to port async
    $tcpobject = New-Object System.Net.Sockets.TcpClient 
    $connect = $tcpobject.BeginConnect($computername,$port,$null,$null)
    
    # wait for the connection no longer than $timeoutMilliseconds 
    $wait = $connect.AsyncWaitHandle.WaitOne($timeoutMilliseconds,$false) 
    
    # return rich information
    $result = @{
        ComputerName = $ComputerName
    }
    
    if(!$wait) { 
        # timeout
        $tcpobject.Close() 
        $result.Online = $false
        $result.Error = 'Timeout'
    } else { 
        try { 
            # try and complete the connection
            $null = $tcpobject.EndConnect($connect)
            $result.Online = $true
        }
        catch { 
            $result.Online = $false
        } 
        $tcpobject.Close() 
    } 
    $tcpobject.Dispose()
    
    [PSCustomObject]$result
} 

Scanning ports is now pretty easy:

 
PS> Get-PortInfo -Port 139 -TimeoutMilliseconds 1000

ComputerName    Online
------------    ------
DESKTOP-7AAMJLF   True
 

PS> Get-PortInfo -Port 139 -TimeoutMilliseconds 1000 -ComputerName storage2

Error   ComputerName Online
-----   ------------ ------
Timeout storage2      False 
 

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!