In this blog post, we will walk through a simple PowerShell script that allows you to set an account expiration date for a user in Active Directory.
The Script
Here is the PowerShell script:
# Prompt the user to enter the username
$username = Read-Host "Enter the username:"
# Prompt the user to enter the account expiration date in the specified format
$dateString = Read-Host "Enter the account expiration date in the format 'MM/dd/yyyy hh:mm AM/PM':"
# Convert the user input into a DateTime object using the ParseExact method
$time = [DateTime]::ParseExact($dateString, "MM/dd/yyyy hh:mm tt", $null)
# Get the AD user object for the specified username and retrieve the AccountExpirationDate property
$user = Get-ADUser -Identity $username -Properties "AccountExpirationDate"
# Set the AccountExpirationDate property of the user account to the specified date and time
$user.AccountExpirationDate = $time
# Update the user account in Active Directory with the new AccountExpirationDate value
Set-ADUser -Instance $user
How It Works
Prompt for Username: The script begins by prompting the user to enter a username. This is the username of the account for which the expiration date will be set.
Prompt for Expiration Date: Next, the script prompts the user to enter an account expiration date in the format ‘MM/dd/yyyy hh:mm AM/PM’.
Convert Input to DateTime: The user input is then converted into a DateTime object using the
ParseExact
method.Retrieve User Object: The script retrieves the Active Directory (AD) user object for the specified username and the
AccountExpirationDate
property.Set Expiration Date: The
AccountExpirationDate
property of the user account is set to the specified date and time.Update User Account: Finally, the user account in Active Directory is updated with the new
AccountExpirationDate
value.
Conclusion
This script provides a simple and effective way to set an account expiration date for a user in Active Directory. However, please ensure you have the necessary permissions to execute these commands in your environment. Also, error handling is not present in this script, so you might want to add that for a production environment. Happy scripting!
Comments
Post a Comment