首页 > 解决方案 > 获取 GPO 设置值

问题描述

我想在 Windows Server 2019 中获取 GPO 策略的设置,例如“帐户:将本地帐户使用空白密码限制为仅控制台登录”。

通常的方法是在本地组策略编辑器中手动转到此路径。

计算机配置\Windows 设置\安全设置\本地策略\安全选项\帐户:将本地帐户使用空白密码限制为仅控制台登录

但是,有没有办法通过 Powershell 获取值?我试过使用 Get-GPOReportgpresult /R但两个结果都不是我想要的。

标签: powershellgroup-policygpowindows-server-2019

解决方案


所以我前段时间为此写了一个函数

Function Parse-SecPol($CfgFile){ 
    secedit /export /cfg "$CfgFile" | out-null
    $obj = New-Object psobject
    $index = 0
    $contents = Get-Content $CfgFile -raw
    [regex]::Matches($contents,"(?<=\[)(.*)(?=\])") | %{
        $title = $_
        [regex]::Matches($contents,"(?<=\]).*?((?=\[)|(\Z))", [System.Text.RegularExpressions.RegexOptions]::Singleline)[$index] | %{
            $section = new-object psobject
            $_.value -split "\r\n" | ?{$_.length -gt 0} | %{
                $value = [regex]::Match($_,"(?<=\=).*").value
                $name = [regex]::Match($_,".*(?=\=)").value
                $section | add-member -MemberType NoteProperty -Name $name.tostring().trim() -Value $value.tostring().trim() -ErrorAction SilentlyContinue | out-null
            }
            $obj | Add-Member -MemberType NoteProperty -Name $title -Value $section
        }
        $index += 1
    }
    return $obj
}

Function Set-SecPol($Object, $CfgFile){
   $SecPool.psobject.Properties.GetEnumerator() | %{
        "[$($_.Name)]"
        $_.Value | %{
            $_.psobject.Properties.GetEnumerator() | %{
                "$($_.Name)=$($_.Value)"
            }
        }
    } | out-file $CfgFile -ErrorAction Stop
    secedit /configure /db c:\windows\security\local.sdb /cfg "$CfgFile" /areas SECURITYPOLICY
}
  
$SecPool = Parse-SecPol -CfgFile C:\test\Test.cgf
$SecPool.'System Access'.PasswordComplexity = 1
$SecPool.'System Access'.MinimumPasswordLength = 8
$SecPool.'System Access'.MaximumPasswordAge = 90

Set-SecPol -Object $SecPool -CfgFile C:\Test\Test.cfg

Parse-SecPol将创建一个文件-CfgFile {FileName},然后从 Config 创建一个 PSObject

Set-SecPol将 PSObject-Object {Parse-SecPol Object}转回 Configfile-CfgFile {FileName}并更新 GPO


推荐阅读