Created
September 28, 2020 14:02
-
-
Save pvanderwoude/3c68ad1a77632f8b9b8aab0c901a5ed7 to your computer and use it in GitHub Desktop.
Remediate-LocalAdministrators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Define variables | |
$currentUser = (Get-CimInstance Win32_ComputerSystem).Username -replace '.*\\' | |
$localAdministrators = @("[YourGlobalAdminRoleSid]","[YourDeviceAdminRoleSid]") #Adjust to your local administrators | |
try { | |
$administratorsGroup = ([ADSI]"WinNT://$env:COMPUTERNAME").psbase.children.find("Administrators") | |
$administratorsGroupMembers = $administratorsGroup.psbase.invoke("Members") | |
foreach ($administratorsGroupMember in $administratorsGroupMembers) { | |
$administrator = $administratorsGroupMember.GetType().InvokeMember('Name','GetProperty',$null,$administratorsGroupMember,$null) | |
if (($administrator -ne "Administrator") -and ($administrator -ne $currentUser)) { | |
$administratorsGroup.Remove("WinNT://$administrator") | |
Write-Host "Successfully removed $administrator from Administrators group" | |
} | |
} | |
foreach ($localAdministrator in $localAdministrators) { | |
$administratorsGroup.Add("WinNT://$localAdministrator") | |
Write-Host "Successfully added $localAdministrator to Administrators group" | |
} | |
Write-Host "Successfully remediated the local administrators" | |
} | |
catch { | |
$errorMessage = $_.Exception.Message | |
Write-Error $errorMessage | |
exit 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment