2

I've written a script to get port information on a single port. The script pipes 'netstat -anob' into a variable then uses Where-Object to scan the object for the exact port number and spit back the desired info.

Unfortunately, the only conditional parameter I use that gets a positive result is -match. But it also yields false positives.

$netstatport = $netstat | Where-Object { $_ -match $port }

If the port I'm searching for is, for example, 555, then the info is found. But the same info is also found if $port is equal to 55. In other words, what I need is:

$port = 55 >> False

$port = 555 >> True

$port = 5555 >> False

I've tried various conditions like -eq, -ieq, =, and so on. Only -match works, but it's too imprecise.

What am I missing?

1
  • 1
    Did you try Where-Object {$_ -match "\b"+$port+"\b"} or Where-Object {$_ -match "\b$port\b"}? Commented Apr 14, 2015 at 20:55

3 Answers 3

2

You can use \b to match at word boundary:

$netstatport = $netstat | Where-Object { $_ -match "\b$port\b"} 

This way, you will not match 555 or 5555 if you pass just 55.

Sign up to request clarification or add additional context in comments.

2 Comments

"\b$port\b" is sufficient, PowerShell will automatically expand the $port variable
It does, as long as you use double quotes :)
0

Regular expressions are supported by the -match operator.

$port = 55
$regex= ":$port\s"
$netstat = Where-Object { $_ -match $regex}

Breaking down the regex:

  • : - character representing the port delimiter in netstat output
  • $port - variable containing the port number you specify
  • \s - single white space after the port number

Note that this pattern will return values that match both local and foreign IP addresses/port numbers.

Comments

0

You should be careful with taking parameter/user input and using it directly in a regular expression, because any special characters will be interpreted, and you can't predict which ones will be present.

Therefore you should escape it with [RegEx]::Escape():

$escPort = [RegEx]::Escape($port)
$netstat | Where-Object { $_ -match "\b$escPort\b" }

(This uses \b but it's the same principle if you want to use something more specific like the other answer)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.