'How to check for value in powershell cmdlet output? [duplicate]
Please explain how I can check the output of the value DynamicPortRangeStartPort in the get-nettcpsetting cmdlet.
The output looks like this:
get-nettcpsetting | select DynamicPortRangeStartPort
DynamicPortRangeStartPort
-------------------------
1024
1024
1024
1024
1024
The cmdlet returns an array of settings, and I just want to check if DynamicPortRangeStartPort is the value 1024 on any of the returned items.
I'm not sure what I'm missing.
I've tried:
if ((get-nettcpsetting | Select DynamicPortRangeStartPort)[1] -eq 1024) { write-host "Yes" }
(get-nettcpsetting | select DynamicPortRangeStartPort) -contains "1024"
(get-nettcpsetting | select DynamicPortRangeStartPort) -in "1024"
(get-nettcpsetting | select DynamicPortRangeStartPort).Contains(1024)
(get-nettcpsetting | select DynamicPortRangeStartPort).Contains("1024")
Forgive my ignorance...
Solution 1:[1]
I discovered that Select DynamicPortRangeStartPort returns an array of objects with exactly one property (DynamicPortRangeStartPort).
Instead, I can use Select -ExpandProperty DynamicPortRangeStartPort to generate a stream of values, rather than a stream of objects with a property.
if ((get-nettcpsetting | Select -Expandproperty DynamicPortRangeStartPort) -contains (1024)) { write-host "Yes" }
As mentioned in a comment, Where-Object also works:
if(Get-NetTCPSetting | Where DynamicPortRangeStartPort -eq 1024){ Write-Host "Yes" }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Appleoddity |
