James Brown
James Brown

Reputation: 347

How to match a precise number within a string with PowerShell?

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?

Upvotes: 2

Views: 530

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626804

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.

Upvotes: 2

briantist
briantist

Reputation: 47792

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)

Upvotes: 0

Bryan
Bryan

Reputation: 17693

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.

Upvotes: 0

Related Questions