A Simple Network Port Scanner in PowerShell

Here is another awesome sample from PowerShell.com that shows how powerful PowerShell can be. It’s a simple Network Port Scanner that scans a remote computer to find if that computer is accessible via a given network port.

See the code below for your reference but you can also skip to the bottom to download the source code and run it to see how it works as well. Basically, by engaging the Windows .Net network socket TcpClient, the script is able to make a connection to a remote computer via certain given port. If connects, it returns True as an indication that the port is open on the remote computer. Or, if times out, it returns False as an indication that the port is closed.

#requires -Version 1
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 
}
}

The script takes a remote computer name or IP address, and optionally a port number and timeout. The default port is 5985, which is used for PowerShell remoting as well as Windows Remote Managment (WinRM). For example:

Windows PowerShell ISE - 2015-12-21 23_32_49

It’s quite fascinating seeing what PowerShell can do. Simply download the file from below andRun it with PowerShell from the context menu.

Kent Chen

Microsoft MVP, IT Professional, Developer, Geek, and the co-founder of Next of Windows.

Last updated: 12/21/2015

Posted in: Tips & Tricks
Discover more: , ,