To achieve the task of generating an Excel file with a date stamp that lists all user logon names under Active Directory (AD) based on the specified requirements, you can use the following PowerShell script. This script assumes you have the necessary permissions to query AD and that you have Excel installed on your system.
Before running the script, ensure you have the Active Directory module for PowerShell installed. You can install it via the following command if you haven't already:
Install-WindowsFeature RSAT-AD-PowerShell
Or, for Windows 10/11, you can install it via Features on or off.
Here's the PowerShell script:
# Import necessary modules
Import-Module ActiveDirectory
# Define the path where the Excel file will be saved
$filePath = "C:\Users\$env:USERNAME\Desktop\AD_Users_$(Get-Date -Format yyyyMMddHHmmss).xlsx"
# Retrieve users based on the criteria
$users = Get-ADUser -Filter * -Properties PasswordNeverExpires, DistinguishedName |
Where-Object {
$_.Enabled -eq $true -and
$_.PasswordNeverExpires -eq $true -and
(
(Get-ADGroups -Identity $_.DistinguishedName -Recursive | Where-Object { $_.Name -like "*admin*" -or $_.Name -like "*system*" }) -or
($_.DistinguishedName -like "*admin*" -or $_.DistinguishedName -like "*system*")
)
} |
Select-Object SamAccountName, Name, DistinguishedName
# Export to Excel
$users | Export-Excel -Path $filePath -TableName "ADUsers" -TableStyle "Medium6"
Write-Host "Excel file has been generated: $filePath"
Please note the following:
- The script uses the
Export-Excel cmdlet, which is part of the ImportExcel module. If you don't have this module installed, you can install it using Install-Module -Name ImportExcel.
- The script saves the Excel file to the desktop of the current user with a filename that includes a timestamp.
- The
-Recursive parameter in Get-ADGroups is used to fetch all groups the user is a member of, including nested groups.
- Ensure you run PowerShell with sufficient permissions to query AD and write to the file system.
Before running the script, make sure to test it in a non-production environment to verify it meets your specific requirements and to avoid any unintended effects on your AD or file system.