How to query for netstat info using PowerShell
In a few earlier posts I have mentioned that machines can run out of ports, for example:
“Nested RecordSet and the port/socket in TIME_WAIT problem by example.“
Normally the idea is that you run something like this:
netstat -aonp tcp -> C:\Temp\NetstatOut.txt
from the command prompt, this will write to a file and then you manually have to count the number of ports in a particular state.
So I thought, should this be possible to do in PowerShell?
Well, it is and here is how you do it.
Start a PowerShell command prompt, then if you wish to check how many TCP ports you have in the TIME_WAIT state, then simply run the following:
$c = netstat -aonp TCP | select-string "TIME_WAIT"; $c.count
This should output number of ports in that particular state.
But why stop there (really because I wanted to get into Powershell a bit more) and not do it for some of the other states that TCP ports can be in.
Simply create a new file (C:\Temp\Netstat.ps1). In this file insert the following:
# Object to contain output
$info = new-object system.text.stringbuilder
#Time when script is executing
$currentTime = get-date -uformat '%Y.%m.%d_%H_%M_%S'
$info.AppendLine("Script ran at : " + $currentTime)
$OSInfo = Get-WmiObject -class Win32_OperatingSystem
$info.AppendLine("Machine info : " + $OSInfo.Caption + " " + $OSInfo.OSArchitecture + " " + $OSInfo.Version)
$info.AppendLine("`nPorts and states:")
#Loop over the states in the array, add/remove states as needed
$stateList = "LISTENING", "TIME_WAIT", "ESTABLISHED"
foreach($s in $stateList)
$c = netstat -aonp TCP | select-string $s
if($c.count -le 0)
$info.AppendLine("0`t" + " ports in state " + $s)
$info.AppendLine($c.count.ToString() + "`t" + " ports in state " + $s)
$toFile = $args
if($toFile -eq "NoFile")
# Create directory if it doesn't exist and setup file for output
$outDir = "C:\NetStatReport\"
if((Test-Path $outDir) -eq $FALSE)
New-Item $outDir -type directory
# Create file and write info
$outFile = $outDir + "PortReport_"+$currentTime+".txt"
New-Item $outFile -type file -force
$info.ToString() | out-file $outFile -append
# To prompt
"File written to :" + $outFile
And save it. Then open the Powershell command window and first navigate to where the file is:
Then execute the script like so:
This will create a directory (C:\NetstatReport) and then log output to a file as well as displaying the output.
If you do not want a file to be created, simply run it with.
You may have to set the execution policy in order to be able to run the script. More on this here:
"Using the Set-ExecutionPolicy Cmdlet"