难以让多行 Powershell 正则表达式工作 - 没有匹配项

难以让多行 Powershell 正则表达式工作 - 没有匹配项

我参考了几个我可以搜索到的例子,这些例子看起来非常中肯,但仍然无法让它发挥作用。

我的输入看起来像这样,来自 dhcp 服务器统计命令,并且我已经确认 $output 已正确定义,其行如下:

MIBCounts:
        Discovers = 63911.
        Offers = 3903.
        Delayed Offers = 0.
        Requests = 29199.
        Acks = 273080.
        Naks = 71.
        Declines = 0.
        Releases = 395.
        ServerStartTime = Tuesday, March 27, 2012 7:38:53 PM
        Scopes = 34.
        Scopes with Delay configured= 0.
        Subnet = 10.31.0.0.
                No. of Addresses in use = 203.
                No. of free Addresses = 40774.
                No. of pending offers = 0.
        Subnet = 10.32.3.0.
                No. of Addresses in use = 0.
                No. of free Addresses = 0.
                No. of pending offers = 0.
        Subnet = 10.32.100.0.
                No. of Addresses in use = 48.
                No. of free Addresses = 145.
                No. of pending offers = 0.
        Subnet = 10.32.101.0.
                No. of Addresses in use = 34.
                No. of free Addresses = 159.
                No. of pending offers = 0.

所以我尝试了以下方法,但没有匹配:

$output=$(netsh -r myserver dhcp server show mibinfo)

$dhcp_regex=@"
(?s)Subnet = (\d\.\d\.\d\.\d)\.\W+
.*No\. of Addresses in use = (\d+)\.\W+
.*No\. of free Addresses = (\d+)\.\W+
"@

$dhcp_record= {
    @{
        subnet=$matches[0]
        inuse=$matches[1]
        free=$matches[2]
    }}


$output -match $dhcp_regex

$matches

非常感谢您的帮助。

答案1

尝试一下第一行:

(?s)Subnet = (\d+\.\d+\.\d+\.\d+)\.\W*

您还需要分别查看每一行:

$output | % { $_ -match $dhcp_regex }

#| Out-Null如果您不想在屏幕上打印每一行,请附加。

$匹配[1]

编辑:这是一个更完整的例子。

$dhcp_regex = 'Subnet = (\d+\.\d+\.\d+\.\d+)'
$dhcp_regex2 = 'in use = (\d+)'
$output | ? { $_ -match $dhcp_regex -or $_ -match $dhcp_regex2} | % { $Matches[1] }

编辑:这是一个多行示例。

$dhcp_regex = '(?m)Subnet = (\d+\.\d+\.\d+\.\d+)\.\r\n.*in use = (\d+)'
$output | Out-String | % { $_ -match $dhcp_regex }
$matches

提示:http://www.vistax64.com/powershell/80160-powershell-regex-help.html

编辑:看起来(?m)实际上没有必要。Out-String是秘密武器。

答案2

更改您提供的正则表达式以添加额外的数据元素。

$dhcp_regex='(?m)Subnet = (\d+\.\d+\.\d+\.\d+)\.\r\n.*in use = (\d+)\.\r\n.* free Addresses = (\d+)\.'

现在一切正常 - 非常感谢!我可能会在无聊的时候花一些时间(呵呵)来发现我们之前所做的事情在哪些细微之处失败了。

相关内容