Account expiry for bulk users in active directory with powershell script
Вставка
- Опубліковано 18 вер 2024
- PowerShell script that reads user information from a CSV file and sets the account expiration date to two days from the current date for each user in Active Directory. Please make sure to adjust the CSV file structure according to your needs:
Please ensure that your CSV file (Users.csv) has a header row with the column Username containing the usernames for which you want to set the expiration date.
Note: Make sure to test scripts in a safe environment before applying them to a production Active Directory. Ensure that you have the necessary permissions to modify user account information.
You can copy the PowerShell script from below URL:
www.infoalias....
#powershell
#powershellscripting
#powershelltraining
#activedirectory
#windows
#server
This worked for me. Thanks! 😁
Question - how do we output the results to a csv file, confirming the expiry date that we set to each user?
# Import the Active Directory module
Import-Module ActiveDirectory
# Specify the path to the CSV file containing user information
$csvFilePath = "C:\Path\To\Your\Users.csv"
# Specify the path for the output CSV file
$outputCsvFilePath = "C:\Path\To\Your\Output.csv"
# Read user information from the CSV file
$userData = Import-Csv $csvFilePath
# Initialize an array to store output data
$outputData = @()
# Function to set account expiration date for AD user and return the result
function Set-ADUserExpiryDate {
param (
[string]$username,
[int]$daysToAdd
)
$user = Get-ADUser -Identity $username
if ($user) {
$expiryDate = (Get-Date).AddDays($daysToAdd)
Set-ADAccountExpiration -Identity $username -DateTime $expiryDate
# Prepare the output object
$outputObject = [PSCustomObject]@{
Username = $username
ExpiryDate = $expiryDate
Status = "Success"
}
} else {
# Prepare the output object for a user not found case
$outputObject = [PSCustomObject]@{
Username = $username
ExpiryDate = $null
Status = "User not found"
}
}
# Return the output object
return $outputObject
}
# Loop through each user in the CSV and set the expiration date
foreach ($user in $userData) {
$result = Set-ADUserExpiryDate -username $user.Username -daysToAdd 2
$outputData += $result
}
# Export the output data to a CSV file
$outputData | Export-Csv -Path $outputCsvFilePath -NoTypeInformation
Write-Host "The operation is complete. Results saved to $outputCsvFilePath"
@@InfoAlias Great! I couldn't get mine to work - I can only get the output to show on the console. This one works - it does give an error message for the names it cannot find, but as long as it feeds the names into the csv file, I am happy. Nice one!
Great, now how do we remove the expiration date?