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:
It’s quite fascinating seeing what PowerShell can do. Simply download the file from below andRun it with PowerShell from the context menu.
75
Outbound port 45.60.45.167:75 is closed.
76
Outbound port 45.60.45.167:76 is closed.
77
Outbound port 45.60.45.167:77 is closed.
78
Outbound port 45.60.45.167:78 is closed.
79
Outbound port 45.60.45.167:79 is closed.
80
Outbound port 45.60.45.167:80 is open.
81
Outbound port 45.60.45.167:81 is open.
82
Outbound port 45.60.45.167:82 is open.
83
Outbound port 45.60.45.167:83 is open.
84
Outbound port 45.60.45.167:84 is open.
85
Outbound port 45.60.45.167:85 is open.