windows11下使用powershell脚本查询所有监听端口程序
新建文本为temp.ps1
# 获取所有状态为"Listen"的TCP连接
$listeningPorts = Get-NetTCPConnection -State Listen
# 遍历这些连接
$results = foreach ($conn in $listeningPorts) {
$procId = $conn.OwningProcess
$localPort = $conn.LocalPort
$process = Get-Process -Id $procId -ErrorAction SilentlyContinue
$services = Get-WmiObject Win32_Service | Where-Object {$_.ProcessId -eq $procId} | Select-Object Name, DisplayName
# 检查进程和服务信息
if ($process) {
[PSCustomObject]@{
LocalPort = $localPort
ProcessName = $process.Name
PID = $procId
ExecutablePath = $process.Path
Services = ($services | ForEach-Object { $_.DisplayName }) -join ", "
}
} else {
# 如果没有找到进程,仍然创建一个对象,只不过进程信息标记为未找到
[PSCustomObject]@{
LocalPort = $localPort
ProcessName = "Process not found"
PID = $procId
ExecutablePath = "N/A"
Services = "N/A"
}
}
}
# 输出所有结果
$results | Format-Table -Property LocalPort, ProcessName, PID, ExecutablePath, Services -AutoSize
在powershell 中调用temp.ps1