Forum Discussion
ianicepi
Jul 24, 2024Copper Contributor
Getting local admins from all PCs
Hello, I am new to power shell scripting and i got a task where i need to restive all the users that have local admins on their devices. Any help? I managed to create a script but i got erro...
sdtslmn
Jul 24, 2024MCT
check the following hope it helps to improve your script
# Function to get local admins for a single computer
function Get-LocalAdmins {
param(
[string]$computerName
)
try {
# Use Get-WmiObject to retrieve local administrators more reliably
$admins = Get-WmiObject -Class Win32_GroupUser -ComputerName $computerName -Filter "GroupComponent='Win32_Group.Domain=\"$computerName\",Name=\"Administrators\"'"
if ($admins) {
foreach ($admin in $admins) {
$account = Get-WmiObject -Class Win32_UserAccount -ComputerName $computerName -Filter "Name='$($admin.PartComponent -split ',')[1]'"
[PSCustomObject]@{
Device = $computerName
User = $account.Name
IsAdmin = $true
}
}
}
}
catch {
Write-Warning "Failed to get local admins for $computerName: $_"
# Optionally, send error details to your Flow
}
}
# Get all computer names in your domain or desired scope
$computerNames = Get-ADComputer -Filter * | Select-Object -ExpandProperty Name
# Process each computer
foreach ($computerName in $computerNames) {
$admins = Get-LocalAdmins -computerName $computerName
if ($admins) {
# Convert admin data to JSON and send to your Flow
$body = ConvertTo-Json $admins
Invoke-RestMethod -uri $URI -Method Post -body $body -ContentType 'application/json'
}
}