Created
August 11, 2022 16:20
-
-
Save jamiechalmerzlp/838d5f2fbefc6ffc07a12a0a120176e2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function get-localadmins{ | |
[cmdletbinding()] | |
Param( | |
[string]$computerName | |
) | |
$group = get-wmiobject win32_group -ComputerName $computerName -Filter "LocalAccount=True AND SID='S-1-5-32-544'" | |
$query = "GroupComponent = `"Win32_Group.Domain='$($group.domain)'`,Name='$($group.name)'`"" | |
$list = Get-WmiObject win32_groupuser -ComputerName $computerName -Filter $query | |
$list | %{$_.PartComponent} | % {$_.substring($_.lastindexof("Domain=") + 7).replace("`",Name=`"","\")} | |
} | |
#Remove the gunk from above | |
cls | |
#Deliver list of local admins into a variable | |
$currentadmins = get-localadmins $env:computername | |
#Define those users that are above the law ! | |
$protectedusersarray = @("Administrator", "Domain Admin", "$env:computername\Administrator", "$env:computername\LocalAdmin", "AzureAD\CloudUser") | |
#DIsplay the contents for us to visually understand | |
write-host "Local users = $currentadmins" | |
write-host "Protected users = $protectedusersarray" | |
write-host "-----------------------------------------------------------------------" | |
# Cycle through each of the discovered admins on this machine | |
Foreach ($finduser in $currentadmins) { | |
#Remove the quotes from front and back of string | |
$finduser = $finduser.Trim('"') | |
# Present the user being searched for and the array being searched in for us to easily see the comparison | |
write-host "-" | |
write-host "Searching for $finduser in $protectedusersarray" | |
# Search and destroy ? | |
$finduser | Where-Object {$_ -notin $protectedusersarray } | Remove-LocalGroupMember administrators | |
} |
Looks good dude!
Thanks mate, I've been getting there quite recently, working on my skills!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks good dude!