Created
March 14, 2026 11:01
-
-
Save panicoenlaxbox/ee8ceb390a87651b0c58f50a09464537 to your computer and use it in GitHub Desktop.
Get-PortInfo.ps1
This file contains hidden or 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
| function Get-PortInfo { | |
| param( | |
| [Parameter(Mandatory)] | |
| [int]$Port, | |
| [switch]$Kill | |
| ) | |
| # Find TCP connections on the specified port | |
| $connections = Get-NetTCPConnection -LocalPort $Port -ErrorAction SilentlyContinue | |
| if (-not $connections) { | |
| Write-Host "Port $Port is free" -ForegroundColor Green | |
| return | |
| } | |
| # Show all connections on that port (there may be multiple) | |
| Write-Host "Connections on port $Port" -ForegroundColor Cyan | |
| $connections | Format-Table LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess -AutoSize | |
| # Keep only those in LISTEN state | |
| $procId = ($connections | Where-Object State -eq 'Listen').OwningProcess | Select-Object -First 1 | |
| if (-not $procId) { | |
| Write-Host "No process is listening on port $Port" -ForegroundColor Yellow | |
| return | |
| } | |
| Write-Host "Listening PID: $procId" -ForegroundColor Yellow | |
| # Process name and executable path | |
| Write-Host "`nProcess" -ForegroundColor Cyan | |
| Get-Process -Id $procId -ErrorAction SilentlyContinue | | |
| Select-Object Id, ProcessName, Path | | |
| Format-List | |
| # Full command line, same as Task Manager > Command line | |
| Write-Host "Command line" -ForegroundColor Cyan | |
| Get-CimInstance Win32_Process -Filter "ProcessId = $procId" | | |
| Format-List ProcessId, Name, CommandLine | |
| # Kill switch: terminate the process if -Kill is passed | |
| if ($Kill) { | |
| Write-Host "Killing process $procId..." -ForegroundColor Red | |
| Stop-Process -Id $procId -Force | |
| Write-Host "Process $procId terminated" -ForegroundColor Green | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment