Set expirationdate with powershell from csv bulk import

The estimated reading time 2 minutes

Set expirationdate with powershell from csv bulk import

In many companies you can find useraccounts which are not used anymore in the company but which are still active. A good option is to provide the account with an expiration date. For this I developed a small script. First of all here is a command to get all accounts in a CSV file output, already with expiration date.
Of course, the “Search-Base” parameter must be adapted for the respective OU structure!

Get-ADUser -Filter * -SearchBase "OU=DEMO,DC=demo01,DC=it-koehler,DC=com" -Properties AccountExpirationDate | Select-Object Surname,Givenname,AccountExpirationDate |Export-Csv -Path C:\Temp\expdate-list.csv -Force -Encoding UTF8

This CSV file could now be maintained by humanressources staff or other departments with the employee’s exit date.
Now here the script, which reads the CSV file and uses this information to set the expiration date of the account.
Caution: if no date is set in the CSV, the user will delete the existing expiration date!

In the script, the two variables “$OU” and “$CSVPATH” must be adjusted, where OU is the distinguished name of the OU to be searched.

#import activedirecory module 
Import-Module ActiveDirectory
#import csv file 
$csvpath = "C:\temp\expdate-list.csv"
$users = Import-Csv -Path "$csvpath" -Encoding UTF8
$ou = "OU=DEMO,DC=demo01,DC=it-koehler,DC=com"
Write-Host "following users will be changed: " -ForegroundColor Gray
foreach($user in $users )
{
 $surname = ($user).Surname 
 $givenname = ($user).GivenName 
 $expdate = ($user).AccountExpirationDate 
 #check if date is not empty
 if($expdate -ne "$null"){
 get-aduser -Filter {(GivenName -eq $givenname) -and (Surname -eq $surname)} -SearchBase "$ou" | Set-ADUser -AccountExpirationDate $expdate
 Write-Host "expirationdate for user $givenname,$surname set to $expdate" -ForegroundColor Green
 }
 else {
 get-aduser -Filter {(GivenName -eq $givenname) -and (Surname -eq $surname)} -SearchBase "$ou" | Set-ADUser -AccountExpirationDate $null
 Write-Host "expirationdate deleted for: $givenname,$surname " -ForegroundColor Yellow
  }
 }
#show overview 
Write-Host " "
Write-Host "overview:"
Get-Aduser -Filter * -SearchBase "$ou" -Properties AccountExpirationDate | Sort-Object surname | Select-Object Surname,Givenname,AccountExpirationDate

This script can also run within the ISE on the DomainController. Or directly inside the Powershell console.
Of course, this can be extended and adjusted. For my purposes, however, this was initially sufficient.

Suggestions for improvement are welcome.
Have fun with it.

Was this article helpful?
YesNo
0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Kommentar
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
trackback
2 years ago

[…] Set expirationdate with powershell from csv bulk import … […]