使用Powershell修改本地安全策略

Kiq*_*net 15 powershell local-security-policy

我使用Windows Server 2012.

我可以做这个:

在"管理工具"文件夹中,双击"本地安全策略"图标,展开"帐户策略"并单击"密码策略"

在右侧窗格中,双击"密码"必须满足复杂性要求并将其设置为"已禁用".单击"确定"以保存策略更改.

如何使用Powershell以编程方式执行此操作?

Raf*_*Raf 23

根据@ Kayasax的回答,没有纯粹的PowerShell方式,你必须将secedit包装成Powershell.

secedit /export /cfg c:\secpol.cfg
(gc C:\secpol.cfg).replace("PasswordComplexity = 1", "PasswordComplexity = 0") | Out-File C:\secpol.cfg
secedit /configure /db c:\windows\security\local.sdb /cfg c:\secpol.cfg /areas SECURITYPOLICY
rm -force c:\secpol.cfg -confirm:$false
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的一件事是,导出策略会违反系统安全性,因为它会公开策略并将文件放置在启动卷 c:\secpol.cfg 的根目录中,从而很容易滥用安全性。因此,我不会在生产环境中逐字使用此内容 - 而是使用 $env:userdata 位置来存储临时文件并解析命令行实用程序“${env:appdata}\secpol.cfg”的文件名 (3认同)

Arc*_*Set 7

我决定编写几个函数来简化这个过程。

Parse-SecPol: 将本地安全策略转换为 PsObject。您可以查看所有属性并对对象进行更改。

Set-SecPol: 将Parse-SecPol对象重新转换为配置文件并将其导入到本地安全策略中。

下面是它的用法示例:

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 = 60

Set-SecPol -Object $SecPool -CfgFile C:\Test\Test.cfg
Run Code Online (Sandbox Code Playgroud)