-
-
Save hermesthecat/50eb29a8114584bb7d3b22f3dab74960 to your computer and use it in GitHub Desktop.
Check if a port is active/open/listening in PowerShell.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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