-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathInvoke-Netstat.ps1
49 lines (43 loc) · 1.1 KB
/
Invoke-Netstat.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
$RegexNetstat = @'
(?x)
# parse output from: "netstat -a -n -o
# you do not need to skip or filter lines like: "| Select-Object -Skip 4"
# correctly captures records with empty States
^\s+
(?<Protocol>\S+)
\s+
(?<LocalAddress>\S+)
\s+
(?<ForeignAddress>\S+)
\s+
(?<State>\S{0,})?
\s+
(?<Pid>\S+)$
'@
if (! $NetstatStdout) {
$NetstatStdout = & netstat -a -n -o
}
# If you're on Pwsh7 you can simplify it using null-*-operators
# $NetstatStdout ??= & netstat -a -n -o
function Format-NetStat {
param(
# stdin
[Parameter(Mandatory, ValueFromPipeline)]
[AllowEmptyString()]
[AllowNull()]
[Alias('Stdin')]
[string]$Text
)
process {
if ($Text -match $RegexNetstat) {
$Matches.Remove(0)
$hash = $Matches
$hash['Process'] = Get-Process -Id $hash.Pid
$hash['ProcessName'] = $hash['Process'].ProcessName
[pscustomobject]$Matches
}
}
}
$Stats = $NetstatStdout | Format-NetStat
$stats | Format-Table
'Results were saved to $stats'