PowerShell - 捕获套接字和进程

问题描述:

我想这个小PowerShell脚本每五秒寻找netstat -ano输出,然后在任何IP地址上只过滤端口80上的传出连接,再加上捕获打开套接字的相关进程。 我认为这里的问题是如果输出中有多个条目,那么它不能处理数组。这里缺少什么?任何更好的方式来做到这一点?PowerShell - 捕获套接字和进程

while(1) {netstat -ano | ? {$_ -like "*10.10.10.10:* *:80 *"} | 
    % { 
    $_ -match "\d+$"; 
$matches | ForEach-Object { 
    Get-Process -id $matches[0] | Format-List *; 
    (Get-Process -id $matches[0]).WaitForExit() 
} 
    Start-Sleep -s 5; 
    } 
} 

Shay Levy写了一个函数与netstat信息,可以帮助你过滤了你的信息,并将其输出的方式,会更容易过滤的工作:How to find running processes and their port number

注:我大概知道大多数人如果在页面丢失的情况下发布代码。 Shay正在更新这个页面,因为事情发生了变化或者需要改进(比如增加对IPv6连接的支持),所以我怀疑他会很快把它取下来。

Get-NetworkStatistics

> Get-NetworkStatistics | where Localport -eq 8000 


ComputerName : DESKTOP-JL59SC6 
Protocol  : TCP 
LocalAddress : 0.0.0.0 
LocalPort  : 8000 
RemoteAddress : 0.0.0.0 
RemotePort : 0 
State   : LISTENING 
ProcessName : node 
PID   : 11552