The pattern:
$a = @()
foreach ($x in Get-Thing|..) {
$z = ..
$a += $z
}
is not a great one, because +=
on an array does a lot of in-memory copying of everything to a new array, so it can be surprisingly slow. foreach() {}
can sometimes run faster than | ForEach-Object {}
but if you have a pipeline inside the () part and array addition going on, it's possibly not going to make much difference there. Typical alternatives:
$a = foreach ($x in Get-Thing|..) {
$z = $x...
$z
}
or
$a = Get-Thing | .. | ForEach-Object {
$_..
}
The first half of your script does approximately nothing:
- starts with an array of process objects
- filters out ones with no username, even though the empty usernames wouldn't change anything later on in your script
- selects three properties, copying them from one object into a new custom object, even though the script wasn't going to be affected by the other properties being there.
- takes those same three properties out into a hashtable ..
- converts that hashtable back into a custom object, putting you back where you were after the select.
- puts it back into another array, but slowly.
Original: process objects in an array.
Result: tweaked process objects in an array, changed, but not meaningfully so given the way you use them.
So you could drop all that for just $obj = Get-Process -IncludeUsername
and it would work the same.
- You don't need as many backticks for line continuation. PowerShell is pretty good at continuing lines where it makes sense - after pipes
|
, and after commas in arrays, including select
property arrays. It's good because the backtick breaks if there are any spaces after it, which is hard to see.
But if you want pre-processing to make the rest of the script nicer, use a hashtable, then the lookup in the second part becomes shorter and clearer:
# Make a lookup table by process ID
$Processes = @{}
Get-Process -IncludeUserName | ForEach-Object {
$Processes[$_.Id] = $_
}
Get-NetTCPConnection |
Where-Object { $_.State -eq "Established" } |
Select-Object RemoteAddress,
RemotePort,
@{Name="PID"; Expression={ $_.OwningProcess }},
@{Name="ProcessName"; Expression={ $Processes[[int]$_.OwningProcess].ProcessName }},
@{Name="UserName"; Expression={ $Processes[[int]$_.OwningProcess].UserName }} |
Sort-Object -Property ProcessName, UserName |
Format-Table -AutoSize
Anyway, now this comes out as the same answer as @avvi, I had to stop with it written but broken because I couldn't make it work until I saw their answer - Get-Process returns the Id as a number and Get-NetTCPConnection returns the OwningProcess as a string, so there needs to be a conversion for the hashtable lookup.
Posting anyway for the discussion about the looping / array building.