To create a PowerShell script that reads a file with a list of usernames and prints the account expiration date for each one, you can use the Get-ADUser cmdlet, which is part of the Active Directory module for Windows PowerShell. This script assumes you have the necessary permissions to query Active Directory and that the module is installed on your system.
Here's a sample PowerShell script that accomplishes this task:
powershell
# Define the path to the file containing the usernames
$usernamesFilePath = "C:\path\to\usernames.txt"
# Check if the file exists
if (Test-Path $usernamesFilePath) {
# Read the list of usernames from the file
$usernames = Get-Content $usernamesFilePath
# Loop through each username and get the account expiration date
foreach ($username in $usernames) {
try {
# Get the user's account info from Active Directory
$userInfo = Get-ADUser -Identity $username -Properties AccountExpirationDate
# Check if the user has an account expiration date set
if ($userInfo.AccountExpirationDate -ne $null) {
$expirationDate = $userInfo.AccountExpirationDate
} else {
$expirationDate = "Never expires"
}
# Print the username and their account expiration date
Write-Output "Username: $username, Account Expiration Date: $expirationDate"
} catch {
Write-Error "Failed to retrieve account expiration date for user: $username. Error: $_"
}
}
} else {
Write-Error "The file at '$usernamesFilePath' does not exist."
}
To use this script:
Replace C:\path\to\usernames.txt with the actual path to the file containing your list of usernames.
Save the script as a .ps1 file, for example, Get-UserExpirationDates.ps1.
Run the script in PowerShell with proper Active Directory permissions.
Remember to run PowerShell as an administrator and ensure that you have the Active Directory module installed and imported with Import-Module ActiveDirectory. If you don't have the Active Directory module, you can install it through the RSAT (Remote Server Administration Tools) features in Windows.