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
Param([string]$ComputerName,$port = 5985,$timeout = 1000)
$tcpclient = New-Object -TypeName system.Net.Sockets.TcpClient
$iar = $tcpclient.BeginConnect($ComputerName,$port,$null,$null)
$wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
# Close the connection and report the error if there is one
$null = $tcpclient.EndConnect($iar)
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.