Clark Clark - 3 months ago 10
PowerShell Question

Select-String -Quiet not returning True

My script is supposed to get the TCP connection information for VNC and tell me when the connection state is

ESTABLISHED
. I'm stuck on trying to get a return value of
True
when using
Select-String -Quiet
.

PS C:\> $vnc = netstat -ab | select-string "winvnc4.exe" -context 1,0
PS C:\> $vnc

TCP 0.0.0.0:5800 User:0 LISTENING
> [winvnc4.exe]
TCP 0.0.0.0:5900 User:0 LISTENING
> [winvnc4.exe]
TCP [::]:5800 User:0 LISTENING
> [winvnc4.exe]
TCP [::]:5900 User:0 LISTENING
> [winvnc4.exe]

PS C:\> $vnc | Select-String "LISTENING" -quiet

PS C:\> $vnc | Select-String -Pattern "LISTENING" -quiet

PS C:\> $vnc | Select-String "LISTENING" -simplematch -quiet


As you can see, I tried several different parameters to get a result but nothing is returned.

Answer

Your first Select-String produces a list of MatchInfo objects. The information you're after is stored in the Context property of these. You need to expand that before you can run another Select-String on it.

$vnc | Select-Object -Expand Context |
    Select-Object -Expand PreContext |
    Select-String 'LISTENING' -SimpleMatch -Quiet

On PowerShell v3 and newer you can use member enumeration to make that a little more compact:

$vnc | ForEach-Object { $_.Context.PreContext } |
    Select-String 'LISTENING' -SimpleMatch -Quiet
Comments