Managing user privileges is a critical aspect of system administration. PowerShell, a powerful scripting solution for Windows, can significantly streamline this process. In this tutorial, we’ll cover how to retrieve a list of local administrators from computers within an Active Directory (AD) domain using PowerShell.
Before executing the script, ensure the following prerequisites are met:
$PSVersionTable.PSVersion in PowerShell.ActiveDirectory module, typically available on Windows Server with Active Directory role or on Windows client machines through RSAT (Remote Server Administration Tools).Enable-PSRemoting cmdlet.TrustedHosts setting on the computers. This is often necessary in workgroup environments or non-trusted domains.Get-ExecutionPolicy and change it with Set-ExecutionPolicy, though this should be done with an understanding of the security implications.To install RSAT, run PowerShell as Administrator and execute the following command:
Add-WindowsFeature RSAT-AD-PowerShell
In some cases, you may need to download RSAT from the Microsoft website or use the “Add a feature” option in the Settings app in Windows. After installation, ensure that the module is available by running:
Get-Module -ListAvailable -Name ActiveDirectory
If the module is listed, you’re ready to proceed. Open your PowerShell ISE or editor of choice and prepare your script. Here’s a breakdown of the key script sections:
$folderPath, $outputFileName, $dateStamp, $logFileName, $outputFile, and $logFile variables are defined at the top of the script.Run the script in PowerShell. Ensure you execute it with administrative privileges to avoid permission issues.
# Output file and log file paths
$folderPath = "C:\test"
$outputFileName = "groupmembership.csv"
$dateStamp = Get-Date -Format "yyyyMMdd_HHmmss"
$logFileName = "log_$dateStamp.txt"
$outputFile = Join-Path -Path $folderPath -ChildPath $outputFileName
$logFile = Join-Path -Path $folderPath -ChildPath $logFileName
# Function to write a log entry
function Write-Log {
Param ([string]$message)
"$((Get-Date).ToString()): $message" | Out-File $logFile -Append
}
# Check and create output folder
if (-not (Test-Path -Path $folderPath)) {
New-Item -ItemType Directory -Path $folderPath | Out-Null
}
# Initialize the output file without an additional line break
"ComputerName,FQDN,IPAddress,MACAddress,OperatingSystem,LocalAdministrators" | Set-Content $outputFile -Encoding ASCII
# Import the Active Directory module
try {
Import-Module ActiveDirectory -ErrorAction Stop
} catch {
Write-Log "Error importing Active Directory module: $_"
exit
}
# Get all active computers (servers and workstations) from Active Directory
try {
$computers = Get-ADComputer -Filter 'OperatingSystem -like "*Server*" -or OperatingSystem -like "*Windows*"' -Properties DNSHostName, OperatingSystem
} catch {
Write-Log "Error querying Active Directory: $_"
exit
}
# Loop through each computer and get details including operating system
foreach ($computer in $computers) {
try {
# Check if the computer is reachable
if (Test-Connection -ComputerName $computer.DNSHostName -Count 2 -Quiet) {
$scriptBlock = {
try {
$networkInfo = Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IPEnabled = TRUE' | Select-Object -First 1
$ipAddress = $networkInfo.IPAddress[0]
$macAddress = $networkInfo.MACAddress
$os = Get-WmiObject Win32_OperatingSystem | Select-Object -ExpandProperty Caption
$admins = Get-LocalGroupMember -Group "Administrators" -ErrorAction Stop | ForEach-Object { $_.Name }
$adminList = $admins -join ", "
$adminList = $adminList.Trim()
$adminList = $adminList -replace '"', '""'
$props = @{
IPAddress = $ipAddress
MACAddress = $macAddress
OperatingSystem = $os
Admins = """$adminList"""
}
return $props
} catch {
throw "Unable to retrieve information: $_"
}
}
$result = Invoke-Command -ComputerName $computer.DNSHostName -ScriptBlock $scriptBlock -ErrorAction Stop
# Construct the output line with all details
$line = "$($computer.Name.Trim()),$($computer.DNSHostName),$($result.IPAddress),$($result.MACAddress),$($result.OperatingSystem),$($result.Admins)"
Add-Content $outputFile -Value $line -Encoding ASCII
} else {
Write-Log "Could not connect to $($computer.DNSHostName)"
}
} catch {
Write-Log "Error retrieving information for $($computer.DNSHostName): $_"
}
}
# Final log entry
Write-Log "Script execution completed. Check the output at $outputFile"
Want to get the above information without all of the pre-requisites and configurations? Lansweeper scans all users from Microsoft Active Directory, Azure Active Directory or Microsoft 365, as well as automatic agent-based or agentless scanning of all devices in your IT environment. This means you can get a quick and complete overview of all AD, AAD, or M365 users, groups, attributes, and device information in seconds. Simply use the default “Local Administrator Accounts” report to get your complete overview that you can consult at any time.

Discover every single device in your IT environment from Servers to OT devices using flexible agent, agentless or passive scanning, utilize extensive third-party integrations to provide your tech stack with an accurate and comprehensive inventory and utilize Lansweeper’s granular reporting, NIST-based risk insights, organized and dynamic network diagrams, and more – all in a powerful solution to efficiently manage your entire network infrastructure.
Try Lansweeper for free! Easily identify all local admins without scripting. Plus, explore detailed device data in your IT environment.
Explore Lansweeper for free.
No credit card required.