Skip to content

Instantly share code, notes, and snippets.

@gavinhungry gavinhungry/RegFight.ps1
Last active Apr 5, 2018

What would you like to do?
PowerShell script to fight Group Policy and keep registry settings as desired
# PowerShell script to fight Group Policy and keep registry settings as desired
# When taking ownership and removing rights from a registry key are not enough
# The author of this script feels quite satisfied that it is the worst
# PowerShell script ever written. If you agree, please feel free to provide
# suggestions, improvements, alternatives or looks of disapproval.
# Update:
# I originally wrote this in order to fight back against opressive Group
# Policy updates. You may find it easier (as I did!) to just put these
# changes into a Windows batch script:
# REG ADD "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Personalization" /f /v NoLockScreen /t REG_DWORD /d 1
# Create a Scheduled Task to fire it off when Group Policy updates. Use the
# event with ID 8004 in the "Microsoft-Windows-GroupPolicy/Operational" log.
# Copyright (C) 2013-2018 Gavin Lloyd <>
# Released under the terms of the MIT license
$User = New-Object System.Security.Principal.NTAccount($env:UserName)
$SID = $User.Translate([System.Security.Principal.SecurityIdentifier]).value
$RegFight = {
param($regHive, $regLong, $regKey, $setName, $setType, $setVal)
New-PSDrive HKU Registry HKEY_USERS
$regPath = $regHive + ":\" + ($regKey -replace "\\\\","\")
$query = "SELECT * FROM RegistryKeyChangeEvent WHERE Hive='$regLong' AND KeyPath='$regKey'"
# ensure that the registry path exists
if (!(Test-Path "$regPath")) { New-Item -Path "$regPath" }
Set-ItemProperty "$regPath" -Name "$setName" -Value $setVal -Type $setType
Do {
if (!(Test-Path "$regPath")) { New-Item -Path "$regPath" }
$eventName = "RegFight-$setName-" + (Get-Date -UFormat %s)
Register-WmiEvent -Query $query -SourceIdentifier $eventName
Wait-Event -SourceIdentifier $eventName
Unregister-Event -SourceIdentifier $eventName
if (!(Test-Path "$regPath")) { New-Item -Path "$regPath" }
# if the value is not what we want, set it
$val = (Get-ItemProperty -Path "$regPath").$setName
if ($val -ne $setVal) {
Set-ItemProperty "$regPath" -Name "$setName" -Value $setVal -Type $setType
} While(1)
Function RegFight($regHive, $regLong, $regKey, $setName, $setType, $setVal) {
Start-Job -ScriptBlock $RegFight -ArgumentList $regHive,$regLong,$regKey,$setName,$setType,$setVal
# Usage:
# RegFight "HKLM" "HKEY_LOCAL_MACHINE" "SOFTWARE\\Policies\\Microsoft\\Windows\\Personalization" "NoLockScreen" "Dword" 1
Get-Job | Wait-Job
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.