Skip to content

Instantly share code, notes, and snippets.

@hermesthecat
Forked from asheroto/IsPortActive.md
Created March 9, 2022 12:17
Show Gist options
  • Save hermesthecat/50eb29a8114584bb7d3b22f3dab74960 to your computer and use it in GitHub Desktop.
Save hermesthecat/50eb29a8114584bb7d3b22f3dab74960 to your computer and use it in GitHub Desktop.
Check if a port is active/open/listening in PowerShell.
# Copy and paste the below function into PowerShell, then you can check if a port is active/open/listening by typing:
# IsPortActive -Port 22
function IsPortActive() {
[CmdletBinding()]
param (
[Int32]$Port
)
# Check script elevation
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
Write-Warning "Insufficient permissions to run this script. Open the PowerShell console as an administrator and run this script again."
Break
}
# Get open ports
$Results = Get-NetTCPConnection | Where-Object { $_.LocalPort -eq "$Port" } | Select-Object @{Name = "Process"; Expression = { (Get-Process -Id $_.OwningProcess).ProcessName } }, @{Name = "Path"; Expression = { (Get-Process -Id $_.OwningProcess).Path } }, LocalAddress, LocalPort, RemoteAddress, RemotePort, State
# Return Results
Write-Host
if ($Results) {
Write-Host "Port $Port is active!"
$Results
}
else {
Write-Host "Port $Port is NOT active"
Write-Host
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment