allywilson

Get-Netstat

Jul 30th, 2017
1,388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/powershell
  2. function Get-Netstat{
  3.     $netstatCheck = Test-Path "C:\WINDOWS\System32\Netstat.exe"
  4.  
  5.     If($netstatCheck -eq $true){
  6.         $netstat = netstat -n
  7.         $netstat = $netstat[4..$netstat.Count]
  8.         $outputArray = @()
  9.         Foreach ($line in $netstat){
  10.             $line = $line -split ' ' | Where-Object {$_ -ne ""}
  11.             $outputArray += New-Object psobject -Property @{
  12.                 Protocol = $line[0]
  13.                 LocalAddress = $line[1]
  14.                 ForeignAddress = $line[2]
  15.                 State = $line[3]
  16.             }
  17.         }
  18.     }
  19.     Else{ # We assume Linux Netstat if Else, probably won't work on macOS.
  20.         $netstat = netstat -nt
  21.         $netstat = $netstat[3..$netstat.Count]
  22.         $outputArray = @()
  23.         Foreach ($line in $netstat){
  24.             $line = $line -split ' ' | Where-Object {$_ -ne ""}
  25.             $outputArray += New-Object psobject -Property @{
  26.                 Protocol = $line[0]
  27.                 ReceiveQ = $line[1]
  28.                 SendQ = $line[2]
  29.                 LocalAddress = $line[3]
  30.                 ForeignAddress = $line[4]
  31.                 State = $line[5]
  32.             }
  33.         }
  34.     }
  35.     $outputArray #| ft
  36. }
  37. Get-Netstat | ft
Advertisement
Add Comment
Please, Sign In to add comment