PowerShell: Find User Accounts Expiring in 7 days

PowerShell: Find User Accounts Expiring in 7 days

This may help some of you; it looks for accounts within a certain OU and outputs their expiration date and email if their account expires in 7 days (no more, no less!).

# Inspired by: http://gallery.technet.microsoft.com/scriptcenter/Email-Active-Directory-452a5640
# Modified for use by; Salomon Johns
# Find users within a certain OU that have accounts expiring in 7 days (no more, no less)
# Print out the results
Get-QADUser -ou "ou=users,dc=test,dc=domain,dc=local" -includedproperties AccountExpires -sAMAccountName '*' |
ForEach-Object {
	$sevendays = (Get-Date).AddDays(7).ToString('yyyyMMdd')
	$samaccountname = $_.samAccountName
	$mail = $_.email
	$expirationdate = Get-Date $_.AccountExpires -format yyyyMMdd
	if ($expirationdate -eq $sevendays) 
		{
			Write-Host $mail,$expirationdate
		}
	}

Hope this helps out anyone that was looking for something like this. Again I only take credit for modifying it to do what I want to.

Other requirements: http://www.quest.com/powershell/activeroles-server.aspx

Further reading: If you want to change the amount of days to say 15, 21, 30, etc. All you have to do is change the following line:

From:

$sevendays = (Get-Date).AddDays(7).ToString('yyyyMMdd')

To:

$sevendays = (Get-Date).AddDays(14).ToString('yyyyMMdd')

This would in effect change it to search for accounts expiring in two weeks.

2 thoughts on “PowerShell: Find User Accounts Expiring in 7 days

  1. above script is not working. I am get error
    Get-Date : Cannot bind parameter ‘Date’ to the target. Exception setting “Date”: “Object reference not set to an instan
    ce of an object.”
    At C:manikexpiry_date.ps1:7 char:28
    + $expirationdate = Get-Date <<<< $_.AccountExpires -format yyyyMMdd
    + CategoryInfo : WriteError: (:) [Get-Date], ParameterBindingException
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.PowerShell.Commands.GetDateCommand

Comments are closed.

Comments are closed.