首页 > 解决方案 > 是否有一种容易记住的方法来过滤仅知道部分 IP 地址的“Get-NetIPAddress”?

问题描述

最近我一直在做更多关于 Windows VM 和容器的网络工作。这些实例最容易为调试网络问题提供 PowerShell 访问。我知道基本的网络命令,*-Net*但是我很难过滤基于对象的输出。具体来说,我发现自己想过滤Get-NetIPAddress到那些在某个子网中具有 IPAddress 值的对象。当您知道确切的 IPAddress ( Get-NetIPAddress | where IPAddress -eq 127.0.0.1) 并且我已经看到了按子网过滤的方法时,这非常简单,但不是很容易记住的东西。我宁愿不必每次都查看它或安装自定义 PS 模块。所以我的问题是,如何 Get-NetIPAddress以类似于知道确切 IPAddress: 的方式过滤子网中 IP 的输出where IPAddress -eq 127.0.0.1

标签: windowspowershell

解决方案


对于部分匹配,您可以使用-likeor-match运算符。

-like接受通配符匹配。*匹配任意数量的字符。?匹配任何字符之一。[]包含要匹配一次的字符范围。

# 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使用正则表达式。这增加了更多的灵活性和复杂性。.匹配此处的任何字符,因此应使用反斜杠对文字点进行转义。

# 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}'

推荐阅读