Jump to page sections
Here goes my fairly polished attempt at a PowerShell nmap-like program that port scans subnets using CIDR notation or a pre-generated list of IP addresses or computer names. It uses efficient runspaces for concurrency (but Linux nmap should be way faster - sad face). This script should definitely replace this old port scan script that I wrote in a former life, eons ago. It also uses PSipcalc under the hood. It has now been published to the PowerShell gallery (see the download section) and feedback is welcome there or on GitHub, where it also currently resides. It has been out in the wild for a couple of years now and not much feedback has been produced. It seems people are pretty happy with it?When you run it, it will first perform a ping sweep of the specified hosts/IPs/networks - without giving any feedback - the progress bar comes when DNS lookups and port scans begin. Only alive hosts will be port scanned, unless you specify the parameter -ScanOnPingFail, which will make it scan the port(s) on all hosts regardless of ping status.
You can use the -Verbose parameter - to have your screen flooded with activity most of the time. This program is not perfect for runs against single hosts. There is some overhead to support faster execution against '''many''' hosts. But really it's just a matter of 3.5 seconds of sleep time plus otherwise minimal overhead, even with a single host. Still seems faster than Test-Port (albeit with different functionality)To just check for an open port on a single host, you can use something like the code below. This also has the added bonus of using an asynchronous call with a specified timeout in milliseconds ("3000" here).
#$computer, $port = $args[0,1] # assign values to these $mysock = new-object net.sockets.tcpclient $IAsyncResult = [IAsyncResult] $mysock.BeginConnect($computer, $port, $null, $null) measure-command { $succ = $iasyncresult.AsyncWaitHandle.WaitOne(3000, $true) } | % totalseconds $succ $mysock.Connected $mysock.Dispose()
I'm adding that the real Linux utility nmap's ping sweep fails to detect most of my Windows hosts on my home LAN, and only finds 11 "alive" hosts, whereas my PSnmap seemingly finds 21, including many more Windows hosts. In my limited experience with port scanning, I've found that results can vary slightly from time to time, and from host to host you scan from, and depending on the utility you use. I've already seen some discrepancies between nmap and my script.
Superficially tested with PowerShell versions 2, 3, 4 and 5.Screenshot examples of PSnmap
We can see how 639 (382 port/DNS + 257 pings) port scans, pings and DNS lookups are finished in 27 seconds.
Download PSnmap
Earlier versions:
PSnmap.zip.
- 2017-06-08: Uploaded v1.2. Replaced instances of int64 with decimal to support x86 platforms, but I forgot that I use the method ToInt64(). Will look into it later.
- 2016-08-06: Uploaded v1.1. Added sorting of results correctly by IP / computer name using some cleverness. Added throttling of pings since it seemed to be in an infinite loop once during testing, and this made that go away (so did cutting the /23 into two /24's and doing two runs). Possibly breaking change: Changed so multiple IPs or DNS names are in an array rather than a semicolon-joined string. I think it's better design in retrospect. Updated the built-in help with examples.
- PSnmap.ps1.txt - right-click and download (v1.0 - use the module for the latest version).
- PSipcalc.ps1.txt - right-click and download. You also need this PSipcalc script in the same folder as PSnmap.ps1 as it is used internally by PSnmap.ps1 (I have now also packaged it as a module - see above).
PSnmap is also on GitHub. https://github.com/EliteLoser/PSnmap - there's a newer version there at this time of writing. That one has also been published to the PowerShell Gallery. As of 2018-07-24 it's version 1.3.1.
If you have Windows Management Framework 5 or higher (WMF 5 is available for Windows 7 and up), you can install my PSnmap module from the PowerShell gallery, a Microsoft project and online repository for scripts.PSnmap works well with PowerShell Core, currently the latest version is PowerShell 7, on Linux as well.
To install with WMF 5 and up (to get the latest PSnmap module version available), you can simply run this command (requires an internet connection):Install-Module -Name PSnmap #-Scope CurrentUser #-Force
Parameters for PSnmap
# CIDR, IP/subnet, IP, or DNS/NetBIOS name. [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()][string[]] $ComputerName, # Port or ports to check. [int[]] $Port, # Perform a DNS lookup. [switch] $Dns, # Scan all hosts even if ping fails. [switch] $ScanOnPingFail, # Number of concurrent threads. [int] $ThrottleLimit = 32, # Do not display progress with Write-Progress. [switch] $HideProgress, # Timeout in seconds. Causes problems if too short. 30 as a default seems OK. [int] $Timeout = 30, # Port connect timeout in milliseconds. 5000 as a default seems sane. [int] $PortConnectTimeoutMs = 5000, # Do not display the end summary with start and end time, using Write-Host. [switch] $NoSummary # Add service name as collected from IANA to the port number property name. [Switch] $AddServicePowershell Windows Networking
Blog articles in alphabetical order
A
- A Look at the KLP AksjeNorden Index Mutual Fund
- A primitive hex version of the seq gnu utility, written in perl
- Accessing the Bing Search API v5 using PowerShell
- Accessing the Google Custom Search API using PowerShell
- Active directory password expiration notification
- Aksje-, fonds- og ETF-utbytterapportgenerator for Nordnet-transaksjonslogg
- Ascii art characters powershell script
- Automatically delete old IIS logs with PowerShell
C
- Calculate and enumerate subnets with PSipcalc
- Calculate the trend for financial products based on close rates
- Check for open TCP ports using PowerShell
- Check if an AD user exists with Get-ADUser
- Check when servers were last patched with Windows Update via COM or WSUS
- Compiling or packaging an executable from perl code on windows
- Convert between Windows and Unix epoch with Python and Perl
- Convert file encoding using linux and iconv
- Convert from most encodings to utf8 with powershell
- ConvertTo-Json for PowerShell version 2
- Create cryptographically secure and pseudorandom data with PowerShell
- Crypto is here - and it is not going away
- Crypto logo analysis ftw
D
G
- Get rid of Psychology in the Stock Markets
- Get Folder Size with PowerShell, Blazingly Fast
- Get Linux disk space report in PowerShell
- Get-Weather cmdlet for PowerShell, using the OpenWeatherMap API
- Get-wmiobject wrapper
- Getting computer information using powershell
- Getting computer models in a domain using Powershell
- Getting computer names from AD using Powershell
- Getting usernames from active directory with powershell
- Gnu seq on steroids with hex support and descending ranges
- Gullpriser hos Gullbanken mot spotprisen til gull
H
- Have PowerShell trigger an action when CPU or memory usage reaches certain values
- Historical view of the SnP 500 Index since 1927, when corona is rampant in mid-March 2020
- How to check perl module version
- How to list all AD computer object properties
- Hva det innebærer at særkravet for lån til sekundærbolig bortfaller
I
L
M
P
- Parse openssl certificate date output into .NET DateTime objects
- Parse PsLoggedOn.exe Output with PowerShell
- Parse schtasks.exe Output with PowerShell
- Perl on windows
- Port scan subnets with PSnmap for PowerShell
- PowerShell Relative Strength Index (RSI) Calculator
- PowerShell .NET regex to validate IPv6 address (RFC-compliant)
- PowerShell benchmarking module built around Measure-Command
- Powershell change the wmi timeout value
- PowerShell check if file exists
- Powershell check if folder exists
- PowerShell Cmdlet for Splitting an Array
- PowerShell Executables File System Locations
- PowerShell foreach loops and ForEach-Object
- PowerShell Get-MountPointData Cmdlet
- PowerShell Java Auto-Update Script
- Powershell multi-line comments
- Powershell prompt for password convert securestring to plain text
- Powershell psexec wrapper
- PowerShell regex to accurately match IPv4 address (0-255 only)
- Powershell regular expressions
- Powershell split operator
- Powershell vs perl at text processing
- PS2CMD - embed PowerShell code in a batch file
R
- Recursively Remove Empty Folders, using PowerShell
- Remote control mom via PowerShell and TeamViewer
- Remove empty elements from an array in PowerShell
- Remove first or last n characters from a string in PowerShell
- Rename unix utility - windows port
- Renaming files using PowerShell
- Running perl one-liners and scripts from powershell
S
- Sammenlign gullpriser og sølvpriser hos norske forhandlere av edelmetall
- Self-contained batch file with perl code
- Simple Morningstar Fund Report Script
- Sort a list of computers by domain first and then name, using PowerShell
- Sort strings with numbers more humanely in PowerShell
- Sorting in ascending and descending order simultaneously in PowerShell
- Spar en slant med en optimalisert kredittkortportefølje
- Spre finansiell risiko på en skattesmart måte med flere Aksjesparekontoer
- SSH from PowerShell using the SSH.NET library
- SSH-Sessions Add-on with SCP SFTP Support
- Static Mutual Fund Portfolio the Last 2 Years Up 43 Percent
- STOXR - Currency Conversion Software - Open Exchange Rates API