Of course! Here is a comprehensive PowerShell script that meets all your requirements. This script is well-commented to help you understand each step.
Prerequisites
- Active Directory Module: The machine running this script must have the Active Directory module for PowerShell installed. This is typically installed as part of the Remote Server Administration Tools (RSAT) for Active Directory Domain Services.
- ImportExcel Module: This script uses a popular and highly recommended module to create a native Excel (
.xlsx) file without needing Microsoft Excel to be installed.
To install the ImportExcel module, open a PowerShell console as an Administrator and run this command:
Install-Module -Name ImportExcel -Force
The PowerShell Script
You can copy and paste the code below into a .ps1 file (e.g., Generate-PrivilegedUserReport.ps1) and run it from a PowerShell console.
<#
.SYNOPSIS
Generates an Excel report of Active Directory users who meet specific privileged criteria.
.DESCRIPTION
This script queries Active an Directory for users that meet the following conditions:
1. The user account is ENABLED.
2. The user account's password is set to NEVER EXPIRE.
3. The user is a member of a group with "admin" or "system" in its name, OR
4. The user's account is located in an Organizational Unit (OU) with "admin" or "system" in its name.
The final report is saved as an Excel file with a timestamp in the filename.
.NOTES
Author: Your Name / AI Assistant
Last-Updated: 2023-10-27
Requires: ActiveDirectory and ImportExcel PowerShell modules.
#>
# --- SCRIPT CONFIGURATION ---
# Specify the folder path where the Excel report will be saved.
# Example for a shared folder: "\\server\reports"
# Example for a local folder: "C:\ADReports"
$ReportPath = "C:\ADReports"
# --- END OF CONFIGURATION ---
# --- SCRIPT LOGIC (Do not modify below this line unless you know what you're doing) ---
# 1. Import necessary modules
try {
Import-Module ActiveDirectory -ErrorAction Stop
Import-Module ImportExcel -ErrorAction Stop
}
catch {
Write-Host "CRITICAL ERROR: A required PowerShell module is not installed." -ForegroundColor Red
Write-Host "Please ensure both 'ActiveDirectory' and 'ImportExcel' modules are available." -ForegroundColor Yellow
Write-Host "To install ImportExcel, run: Install-Module -Name ImportExcel" -ForegroundColor Yellow
# Exit the script if modules are missing
exit
}
# 2. Prepare file path and name
# Create the report directory if it doesn't exist
if (-not (Test-Path -Path $ReportPath)) {
Write-Host "Report path '$ReportPath' does not exist. Creating it now..." -ForegroundColor Cyan
New-Item -ItemType Directory -Path $ReportPath | Out-Null
}
# Generate a timestamp for the filename
$TimeStamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$FileName = "Privileged_User_Report_$TimeStamp.xlsx"
$FullFilePath = Join-Path -Path $ReportPath -ChildPath $FileName
Write-Host "Starting user query..." -ForegroundColor Green
# 3. Get all users that meet the MUST-HAVE criteria (Enabled AND Password Never Expires)
# This initial filter makes the script much more efficient.
$initialUserFilter = { (Enabled -eq $true) -and (PasswordNeverExpires -eq $true) }
$potentialUsers = Get-ADUser -Filter $initialUserFilter -Properties Name, DistinguishedName, MemberOf
Write-Host "Found $($potentialUsers.Count) users who are enabled and have non-expiring passwords. Now checking detailed criteria..."
# 4. Process each user to check for the OR criteria (Group or OU membership)
$reportData = foreach ($user in $potentialUsers) {
$isGroupMember = $false
$isInOU = $false
# Check #4: Is the user in an OU with "admin" or "system" in the name?
# We split the DistinguishedName and check each OU part
$dnParts = $user.DistinguishedName.Split(',')
foreach ($part in $dnParts) {
if ($part.StartsWith("OU=") -and (($part -like "*admin*") -or ($part -like "*system*"))) {
$isInOU = $true
break # Found a match, no need to check other OUs
}
}
# Check #3: Is the user a member of a group with "admin" or "system" in the name?
foreach ($groupDN in $user.MemberOf) {
# Extract the group name (CN) from its Distinguished Name
# Example: CN=Domain Admins,CN=Users,DC=corp,DC=local -> "Domain Admins"
$groupName = ($groupDN -split ',')[0] -replace 'CN='
if (($groupName -like "*admin*") -or ($groupName -like "*system*")) {
$isGroupMember = $true
break # Found a match, no need to check other groups
}
}
# If the user meets either the Group OR OU criteria, add them to our report list
if ($isGroupMember -or $isInOU) {
# Output a custom object with the details. This will be collected into $reportData.
[PSCustomObject]@{
UserLogonName = $user.SamAccountName
DisplayName = $user.Name
IsInAdminOrSystemOU = $isInOU
IsMemberOfAdminOrSystemGroup = $isGroupMember
DistinguishedName = $user.DistinguishedName
}
}
}
# 5. Generate the Excel Report
if ($reportData.Count -gt 0) {
Write-Host "Found $($reportData.Count) users matching all criteria. Generating Excel report..." -ForegroundColor Green
# Use Export-Excel to create a professional-looking spreadsheet
$reportData | Export-Excel -Path $FullFilePath -WorksheetName "Privileged Users" -AutoSize -BoldTopRow -FreezeTopRow -TableName "UserData"
Write-Host "SUCCESS: Report generated successfully at '$FullFilePath'" -ForegroundColor Green
}
else {
Write-Host "No users were found that match all the specified criteria." -ForegroundColor Yellow
}
How to Use the Script
- Customize the Path: Open the script file in a text editor (like VS Code or Notepad) and change the
$ReportPath variable on line 20 to your desired output folder (e.g., C:\ADReports or a network share like \\fileserver\AuditLogs).
- Run the Script:
- Open a PowerShell console.
- Navigate to the directory where you saved the script file.
- Run the script by typing its name:
.\Generate-PrivilegedUserReport.ps1
- Check the Output: The script will print its progress to the console and will tell you where the final Excel file was saved.
Explanation of the Excel Output
The generated Excel file will contain the following columns, making it easy to see why a user was included in the report:
- UserLogonName: The user's sAMAccountName (the logon name you requested).
- DisplayName: The user's full name for better readability.
- IsInAdminOrSystemOU: A
TRUE or FALSE value indicating if the user is in a matching OU.
- IsMemberOfAdminOrSystemGroup: A
TRUE or FALSE value indicating if the user is in a matching group.
- DistinguishedName: The full AD path to the user object, which is useful for auditing and verification.