Skip to content

Instantly share code, notes, and snippets.

@josamontiel
Created March 1, 2024 23:15
Show Gist options
  • Save josamontiel/95ed2240e6c92bb884012787058310b8 to your computer and use it in GitHub Desktop.
Save josamontiel/95ed2240e6c92bb884012787058310b8 to your computer and use it in GitHub Desktop.
A powershell script that will find all the inactive users in a directory (users who have not logged in for 90 + days) and outputs the results into a csv file.
# Function to check if Active Directory module is installed
function Check-ADModuleInstalled {
if (Get-Module -ListAvailable -Name ActiveDirectory) {
return $true
} else {
Write-Host "Active Directory module is not installed."
return $false
}
}
# Function to retrieve inactive users
function Get-InactiveADUsers {
# Define the number of days for inactive users
$daysInactive = 90
# Get the current date
$currentDate = Get-Date
# Calculate the inactive threshold date
$thresholdDate = $currentDate.AddDays(-$daysInactive)
# Get inactive users
$inactiveUsers = Get-ADUser -Filter {LastLogonDate -lt $thresholdDate} -Properties LastLogonDate | Where-Object { $_.Enabled -eq $true }
return $inactiveUsers
}
# Check if Active Directory module is installed
if (Check-ADModuleInstalled) {
# Retrieve inactive users
$inactiveUsers = Get-InactiveADUsers
if ($inactiveUsers) {
# Define CSV file path
$csvFilePath = "over90Days.csv"
# Output inactive users to CSV
$inactiveUsers | Select-Object SamAccountName, LastLogonDate | Export-Csv -Path $csvFilePath -NoTypeInformation
Write-Host "Results exported to $csvFilePath"
} else {
Write-Host "No inactive users found."
}
}
@josamontiel
Copy link
Author

In this script:

  • The Check-ADModuleInstalled function checks if the Active Directory module is installed. If it is, it returns true; otherwise, it returns false.
  • The Get-InactiveADUsers function retrieves inactive users from Active Directory.
  • The script first checks if the Active Directory module is installed using the Check-ADModuleInstalled function. If it is installed, it proceeds to retrieve inactive users using the Get-InactiveADUsers function and exports the results to a CSV file. If the module is not installed, it displays a message indicating that the module is not installed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment