I have a script that can check local admins and excluding the users that are expected to have the rights to be part of the Local Admin Group and display the result. Is there a way to simplify my script below?
$date = Get-Date -Format "MM-dd-yyy-HHmmss"
$report = "C://Temp/ProvisioningForWSReport-$date.txt"
function LocalAdmins{
[cmdletbinding(SupportsShouldProcess=$True,ConfirmImpact="Low")] Param([parameter(Mandatory=$false)][switch]$Enable)
Begin {
$writeTxt = "$(Get-Date) - Currently checking if there are other users who have admin rights on the machine....";
Write-Output $writeTxt
Add-Content -path $report $writeTxt
}
Process {
$hostname = hostname
net localgroup Administrators >> C:\temp\AdminUsers.txt
$User1 = "Administrator"
$User2 = "user1"
$User3 = "user2"
$Text1 = "Members"
$Text2 = "-------------------------------------------------------------------------------"
$Text3 = "The command completed successfully."
(gc C:\temp\AdminUsers.txt ) | ? {$_.trim() -ne "" } | set-content C:\temp\AdminUsers1.txt
$LocalAdmin = Get-Content C:\temp\AdminUsers1.txt | Select-String -Pattern "$User1", "$User2", "$User3", "$Text1", "$Text2", "$Text3" -NotMatch
$writeTxt = "$(Get-Date) - [INFO] These are the users that have admin rights on the machine: $LocalAdmin ";
Write-Output $writeTxt
Add-Content -path $report $writeTxt
del C:\temp\AdminUsers.txt
del C:\temp\AdminUsers1.txt
}
End {}
}
#####Execute Functions#####
LocalAdmins
Here is the sample output of this script:
Checking if there are other users have the admin rights on the machine...
01/05/2022 13:27:58 - [INFO] These are the users that have admin rights on the machine: User3 User4
Also, how can I display the result like this?
Checking if there are other users have the admin rights on the machine...
01/05/2022 13:27:58 - [INFO] These are the users that have admin rights on the machine: User3, User4
CodePudding user response:
If you have probems using cmdlets like Get-LocalGroupMember, you can filter the output of the net localgroup Administrators command like this:
# get the list of user names that are member of the Administrators group
# remove empty and non usable lines of the output
$adminlist = (net localgroup Administrators) | Where-Object { $_ -match '\S' } | Select-Object -Skip 4 | Select-Object -SkipLast 1
# now filter away the members you do not want to be listed
$notThese = 'Administrator', 'user1', 'user2'
$localAdmins = $adminlist | Where-Object { $notThese -notcontains $_ }
Now you have an array of usernames with admin rights in variable $localAdmins
To create the output you want, just join the array and merge into your string:
"$(Get-Date) - [INFO] These are the users that have admin rights on the machine: {0}" -f ($localAdmins -join ', ')
