PowerShell Script to Audit User Account Security
This PowerShell script audits user accounts in Active Directory to identify accounts that may pose security risks. It checks for accounts that are disabled, expired, or have never been logged into, allowing administrators to take appropriate actions.
Step 1: Import Active Directory Module
To begin, we need to import the Active Directory module which contains the cmdlets necessary for querying user accounts.
Import-Module ActiveDirectory
Using the Import-Module cmdlet, we ensure that our script can access Active Directory functions.
Step 2: Get All User Accounts
Next, we will retrieve all user accounts from Active Directory. This forms the foundation for our security audit.
$users = Get-ADUser -Filter * -Properties Enabled, LastLogonDate, AccountExpirationDate
Here, we use the Get-ADUser cmdlet to gather all user accounts while also retrieving specific properties related to account status.
Step 3: Filter and Analyze User Accounts
In this step, we will filter the user accounts to identify those that are disabled, expired, or have never been logged in.
$problematicUsers = $users | Where-Object { ($_.Enabled -eq $false) -or ($_.AccountExpirationDate -lt (Get-Date)) -or ($_.LastLogonDate -eq $null) }
With this block, we create a collection of accounts that meet our security risk criteria.
Step 4: Display Problematic Users
Now we will display the filtered accounts in a user-friendly format, making it easier for administrators to review the results.
$problematicUsers | Select-Object Name, Enabled, LastLogonDate, AccountExpirationDate | Format-Table -AutoSize
In this block, we use Select-Object to choose specific properties to display, and Format-Table ensures the output is organized neatly.
Step 5: Export Results to CSV
Finally, we can export the list of problematic accounts to a CSV file for further analysis or reporting purposes.
$problematicUsers | Export-Csv -Path 'C:\UserAuditReport.csv' -NoTypeInformation
This command generates a CSV file containing details of the user accounts flagged during the audit, which can be opened in Excel or other programs.
By following these steps, administrators can effectively monitor user accounts in Active Directory, ensuring that potential security risks are addressed promptly. This script serves as a crucial tool for maintaining a secure environment.