PowerShell Script for Security Auditing of User Accounts
In this post, I will share a useful PowerShell script for auditing user accounts on a Windows system. This script checks for user accounts that have not logged in for a specified period, flags accounts that might be stale, and provides a report that can help system administrators maintain security by ensuring only active users have access.
### Step 1: Define Parameters
In this first step, we will define the parameters for our script, including the number of days to check for inactivity.
“`powershell
$InactiveDays = 90 $DateThreshold = (Get-Date).AddDays(-$InactiveDays)
“`
### Step 2: Get All User Accounts
Next, we will retrieve the list of user accounts from the local machine.
“`powershell
$UserAccounts = Get-LocalUser
“`
### Step 3: Filter Inactive Accounts
We will filter the user accounts to find those that have not logged in since the specified threshold date.
“`powershell
$InactiveUsers = $UserAccounts | Where-Object { $_.LastLogon -lt $DateThreshold -or $_.LastLogon -eq $null }
“`
### Step 4: Generate the Report
Now that we have identified the inactive accounts, we will generate a report listing these accounts.
“`powershell
if ($InactiveUsers.Count -eq 0) { Write-Host 'No inactive user accounts found.' } else { $InactiveUsers | Format-Table -Property Name, LastLogon }
“`
### Step 5: Export the Report (Optional)
As a final step, we may want to export the report to a CSV file for further analysis.
“`powershell
$ReportPath = 'InactiveUsersReport.csv' $InactiveUsers | Export-Csv -Path $ReportPath -NoTypeInformation Write-Host "Report exported to $ReportPath"
“`
This simple script allows system administrators to maintain a secure environment by identifying potentially unused accounts. Regular audits of user accounts are essential to prevent unauthorized access and enhance organizational security.