Advertisement
Guest User

https://stackoverflow.com/questions/70175444/how-can-i-show-the-netstat-command-in-powershell-withou

a guest
Dec 1st, 2021
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function Get-Netstat {
  2.  
  3.     # https://www.reddit.com/r/PowerShell/comments/khiwjo/parsing_netstat_ano/
  4.  
  5.     $sb = {
  6.         param($proto,$pcid,$state)
  7.         $localaddr,$localport,$remoteaddr,$remoteport = $_[1..2] |
  8.             Foreach-Object {-split ($_ -replace '(^.+):(.+$)','$1 $2')}
  9.         [PSCustomObject]@{
  10.             Protocol      = $proto
  11.             LocalAddress  = $localaddr
  12.             LocalPort     = $localport
  13.             RemoteAddress = $remoteaddr
  14.             RemotePort    = $remoteport
  15.             ProcessID     = $pcid
  16.             State         = $state
  17.         }
  18.     }
  19.  
  20.     switch -Regex (netstat -ano){
  21.         'TCP' {
  22.             , -split $_ | ForEach-Object {
  23.                 $sb.Invoke($($_[0,4,3]))
  24.             }
  25.         }
  26.         'UDP' {
  27.             , -split $_ | ForEach-Object {
  28.                 $sb.Invoke($_[0],$_[3],'Stateless')
  29.             }
  30.         }
  31.     }
  32. }
  33.  
  34. Get-Netstat | Select-Object @{n='Local Address';e={"{0}{1}" -f ($_.LocalAddress -replace '0\.0\.0\.0'),$_.LocalPort}},ProcessID
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement