首页 > 解决方案 > 获取 GPOReport 并搜索匹配的名称值

问题描述

我正在尝试使用 PowerShell 命令“Get-GPOReport”以 XML 字符串格式获取 GPO 信息,以便可以在其中搜索具有未知和不同元素标记名称的子元素值(我认为 XML 对象格式不起作用对我来说,所以我没有使用“[xml]”执行强制转换),但我无法解析 XML 输出,以便我可以在匹配的所需“名称”元素行之后抓取一两行我正在搜索的文本。

之后,我一直在尝试将“Select-String”或“Select-XML”与 XPath 一起使用(格式不清楚,我不知道是否可以对各种策略记录位置使用格式)来匹配文本并获取值,但我没有任何运气。

此外,如果有人知道如何搜索 GPMC GUI 名称(即“强制密码历史记录”)而不是需要首先找到后端等效名称来搜索(即“PasswordHistorySize”),那也会更有帮助。

以下初始代码是有效的部分:

$String = "PasswordHistorySize"     # This is an example string, as I will search for various strings eventually from a file, but I'm not sure if I could search for equivalent Group Policy GUI text "Enforce password history", if anyone knows how to do that.
$CurrentGPOReport = Get-GPOReport -Guid $GPO.Id -ReportType Xml -Domain $Domain -Server $NearestDC

If ($CurrentGPOReport -match $String) 
{
    Write-Host "Policy Found: ""$($String)""" -Foregroundcolor Green
    #
    #
    # The following code is what I've tried to use to get value data, without any luck:
    #
    $ValueLine1 = $($CurrentGPOReport | Select-String -Pattern $String -Context 0,2)
    $Value = $($Pattern = ">(.*?)</" ; [regex]::match($ValueLine1, $Pattern).Groups[1].Value)
}

标签: powershellparsingsearchmatchgroup-policy

解决方案


从昨天开始我就一直在看这个,不明白为什么Select-String不起作用,今天我想通了……报告存储为多行字符串,而不是字符串数组。您可以-match针对它的值做一个反对,但Select-String不喜欢它看起来的多行格式。如果你-split '[\r\n]+'在上面,你可以Select-String找到你的字符串。

如果您想使用正则表达式来仅狙击设置值,您可以使用多行正则表达式搜索来完成,如下所示:

$String = "PasswordHistorySize"     # This is an example string, as I will search for various strings eventually from a file, but I'm not sure if I could search for equivalent Group Policy GUI text "Enforce password history", if anyone knows how to do that.
$CurrentGPOReport = Get-GPOReport -Guid $GPO.Id -ReportType Xml -Domain $Domain -Server $NearestDC

$RegEx = '(?s)' + [RegEx]::Escape($String) + '.+?Setting.*?>(.*?)<'

If($CurrentGPOReport -match $RegEx)
{
    Write-Host "Policy Found: ""$String""" -Foregroundcolor Green

    $Value = $Matches[1]
}

我不确定如何匹配 GPMC 名称,对此感到抱歉,但这应该会让您更接近您的目标。

编辑:为了尝试将每个设置分离到它自己的文本块中,而不仅仅是在那个策略上工作,我不得不稍微改变我的 RegEx。这个输出有点混乱,但我认为可以简单地清理。这会将 GPO 拆分为单独的设置:

$Policies = $CurrentGPOReport -split '(\<(q\d+:.+?>).+?\<(?:\/\2))' | Where { $_ -match ':Name' }

这将为您提供如下所示的集合:

<q1:Account>
          <q1:Name>PasswordHistorySize</q1:Name>
          <q1:SettingNumber>21</q1:SettingNumber>
          <q1:Type>Password</q1:Type>
        </q1:Account>

从那里你只需要过滤你正在寻找的任何设置。


推荐阅读