Powershell: local admin users checks
Powershell PowershellKeeping control of members in the local admins group can be a chore, especially if you inherit multiple domains who’ve done their own thing for years.
This proactive remediation from intune can help weed out the staff who aren’t supposed to be in the group and remove them.
How it works is by referencing a list ( which can be stored in azure blob storage called excluded.txt, this makes it easy for you to added/remove excluded users.
The detection and remediation scripts reference this.
Detection
Clear-Host
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
#Require Admin Privileges
If (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator"))
{ throw "This script must be run as an administrator." }
$bad = 0
invoke-webrequest -uri "[url to sas storage excluded.txt]" -OutFile c:\Windows\temp\excluded.txt
$excludedmembers = get-content C:\Windows\temp\excluded.txt
$localadmins = get-localgroupmember -Group Administrators | Where-Object { $_.PrincipalSource -ne 'Local' -and $_.objectclass -eq 'user' -and $_.name -ne "$env:userdomain\Domain Admins" } | Select-Object -ExpandProperty Name
foreach ($user in $localadmins) {
if ($excludedmembers -like $user) {
Write-output "$user is excluded, skipping"
}
else {
Write-Output "$user shouldn't be in local admins, removing"
$bad++
#Remove-LocalGroupMember -Group administrators -Member $user -WhatIf -Verbose
}
}
if ($bad -gt 0 ) {
exit 1
} else {
exit 0
}
remove-item C:\Windows\temp\excluded.txt
Remediation
Clear-Host
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
#check local admin accounts
invoke-webrequest -uri "[url to sas storage excluded.txt]" -OutFile "c:\windows\temp\excluded.txt"
$excludedmembers = get-content c:\windows\temp\excluded.txt
$localadmins = get-localgroupmember -Group Administrators | Where-Object { $_.PrincipalSource -ne 'Local' -and $_.objectclass -eq 'user' -and $_.name -ne "$env:userdomain\Domain Admins" } | Select-Object -ExpandProperty Name
foreach ($user in $localadmins) {
if ($excludedmembers -like $user) {
Write-output "$user is excluded, skipping"
}
else {
Write-output "$user shouldn't be in local admins, removing"
Remove-LocalGroupMember -Group administrators -Member $user -Verbose
}
}
exit 0
remove-item C:\Windows\temp\excluded.txt -Force
As always this is also available from my GitHub page.
https://github.com/richeaston/Powershell/tree/main/LocalUserChecks