Reputation: 3714
Recently I have been doing more networking work on Windows VM and Containers. These instances most easily offer PowerShell access for debugging network issues. I know the basic networking commands, *-Net*
, but I am having a hard time filtering the Object based outputs. Specifically I find myself wanting to filter Get-NetIPAddress
to just those objects that have IPAddress values in a certain subnet. This is pretty straight forward when you know the exact IPAddress (Get-NetIPAddress | where IPAddress -eq 127.0.0.1
) and I have seen ways to filter by subnet, but not something that is easy to remember. I'd rather not have to look this up every time or install a custom PS module. So my question is, how can you filter the output of Get-NetIPAddress
for IP's in a subnet in a way similar to how you know the exact IPAddress: where IPAddress -eq 127.0.0.1
.
Upvotes: 0
Views: 1744
Reputation: 25031
For partial matching, you can use the -like
or -match
operator.
-like
accepts wildcard matching. *
matches any number of characters. ?
matches one of any character. []
contains a range of characters to match once.
# Matches 127.0.<anything>
Get-NetIPAddress | where IPAddress -like '127.0.*'
# Matches 127.0.0.<one character>
Get-NetIPAddress | where IPAddress -like '127.0.0.?'
# Matches 127.0.0.<one number between 0 and 9>
Get-NetIPAddress | where IPAddress -like '127.0.0.[0-9]'
-match
uses regex. This adds more flexibility and complexity. .
match any character here so literal dots should be escaped with backslash.
# Matches 127.0.0.<one number between 0 and 9>
Get-NetIPAddress | where IPAddress -match '127\.0\.0\.[0-9]'
# Matches 127.<any number>.<any number>.<any number>
Get-NetIPAddress | where IPAddress -match '127\.[0-9]+\.[0-9]+\.[0-9]+'
# Matches 127.0.<one number between 0 and 9>.<two digit number>
Get-NetIPAddress | where IPAddress -match '127\.0\.[0-9]\.[0-9]{2}'
Upvotes: 2