PowerShell Account Expiration

While writing an user administration script to add users, I noticed that all my new created temporary workers had the wrong Account Expiration date on them, they were all off by a day.

The code in question is the following:

Set-ADUser -Identity $samName -AccountExpirationDate (Get-Date $endDate) -Credential $creds

So what happens is when we pass the $endDate (ie: March 09, 2017) variable it actually passes March 09, 2017 12:00:00 AM. So when we look at the user object with in Active Directory Users and Computers, you'll see that the account expires end of day March 8th. Which makes total sense, but we actually want the account to expire end of day March 9th. So the easiest fix is to do the do this:

Set-ADUser -Identity $samName -AccountExpirationDate ((Get-Date $endDate).AddDays(1)) -Credential $creds

Such a small little thing that I would never have noticed, but when you think about it. It makes a lot of sense why it did what it did, and what we have to do to compensate for it.