powershellregistrypowershell-3.0powershell-4.0gpo

Use PowerShell to check the box to "Remove this item if it is no longer applied" option behavior in Group Policy preferences


I have been exploring using PowerShell to inject a few RegKeys and settings into GPOs and have it pretty much figured out, all except how to check the box for the "Remove this item if it is no longer applied" option behavior in Group Policy preferences. for the life of me, i can't find anything on how to use PowerShell to set that. Can anyone help with this? its becoming a pain to use PowerShell to inject the Reg Settings into the GPOs that I need and then have to go into each GPO and edit them to check the box for "Remove this item if it is no longer applied" in every singe Reg Key added to the GPOs.

for example here is 2 lines of a 30+ line PowerShell I am using to inject the reg settings and need to add the check box for "Remove this item if it is no longer applied"

$GPO = Read-Host -Prompt 'Enter the GPO Name you want to change'

Set-GPPrefRegistryValue -Name "$GPO" -Context Computer -Action Replace -Order 1 -Key "HKLM\SOFTWARE\Microsoft\.NETFramework" -ValueName "AllowStrongNameBypass" -Value 0 -Type DWord

Solution

  • The GroupPolicy module does not allow these settings to be checked.

    The same goes for Item-level targeting etc.

    You can use a third party powershell module (sdmsoftware something) to do things like this. They didn't specify the cost for that online so I wrote something that seems to do the trick.

    I just put this at the bottom of my Set-GPPrefRegistryValue code, at the end of the script.

    Do understand it and evaluate the risk yourself. I haven't had this in production.

    $GPO = Get-GPO -Name $GroupPolicyName -Server $DomainController
    $domain = (($GPO.path -split ",") | where-object {$_ -like "DC=*"}).replace("DC=","") -join "."
    $Path = "\\"+$domain+"\SYSVOL\"+$domain+"\Policies\{"+$gpo.id+"}"+"\Machine\Preferences\Registry\Registry.xml"
    #Should amount to something like this - \\domain.test\SYSVOL\domain.test\Policies\{A235F578-35F1-42D9-9CE7-CB0A74F85C08}\Machine\Preferences\Registry\Registry.xml
    [xml]$xml = Get-Content $Path
    foreach ($regsetting in $xml.registrysettings.registry | where-object {(!($_.removePolicy))}){ #This filter will find any reg entries that do not have "remove this item when it is no longer applied" checked
        $regsetting.SetAttribute("removePolicy","1") #then toggle that box
        $regsetting.SetAttribute("bypassErrors","1") #Don't know why, but when done in GUI this gets toggled as well.
    }
    $xml.save($Path)