Stale User Accounts

Very similar to the Stale Computer Accounts script.

add-PSSnapin quest.activeroles.admanagement

$InactiveDays = "20"

$InactiveFrom = [Math]::Round(( `

 New-TimeSpan $(Get-Date("01/01/1601 00:00:00")) `

 ((Get-Date).AddDays(-$InactiveDays))).TotalSeconds, 0)

$InactiveFrom = "$($InactiveFrom.ToString())0000000"

$noRecentLogonFile = "C:\scripts\noRecentLogonFile.csv"

$LdapFilter = "(&(lastlogon<=$InactiveFrom)(!lastlogon=0))"

$recipientlist = "C:\scripts\recipientlist.txt"

# With http://www.quest.com/powershell/activeroles-server.aspx

Get-QADUser  -enabled -LdapFilter $LdapFilter -IncludedProperties lastlogon `

 | where { $_.'ParentContainer' -ne 'blah.corp/Services' `

   -and $_.'ParentContainer' -ne 'blah.corp/Conference Rooms' `

-and $_.'ParentContainer' -ne 'blah.corp/People/CustomUsers/CRMTraining Accounts' `

 | Select-Object SAMAccountName, Name, phonenumber, lastlogon, PasswordExpires, parentcontainer `

 | sort lastlogon | export-CSV -NoTypeInformation $noRecentLogonFile

#Send an email and attach file

C:\scripts\blat.exe -tf $recipientlist -f kevin@blah.com -s "Users that have not logged on in the last 20 days" -server smtp.blah.com -body "please see the attached file." -attach $noRecentLogonFile

 

Recently logged on Group Members 

Group members that have logged on in the last 90 Days

$date = Get-Date

$date = $date.AddDays(-90)

$recentGroupUsers = Get-QADGroupMember -sl 0 "IDC\Group Blah" | where {$_.lastlogontimestamp -gt $date} | select name, samaccountname, lastlogontimestamp

$recentGroupUsers | measure 

Stale User Accounts

IF (Get-PSSnapin | where {$_.name -eq "quest.activeroles.admanagement"}) 

    {write-host "Quest Active Roles snapin already loaded"}

Else

    {add-PSSnapin  quest.activeroles.admanagement}

$smtpServer = "mail.blah.com"

$From = "AD Reporting <ADReporting@blah.com>"

$To = "Kevin Curran <kcurran@blah.com>"

$Bcc = "Kevin Curran <kcurran@blah.com>"

$InactiveDays = "365"

$InactiveFrom = [Math]::Round(( `

  New-TimeSpan $(Get-Date("01/01/1601 00:00:00")) `

  ((Get-Date).AddDays(-$InactiveDays))).TotalSeconds, 0)

$InactiveFrom = "$($InactiveFrom.ToString())0000000"

$LdapFilter = "(&(LastLogonTimestamp<=$InactiveFrom)(!LastLogonTimestamp=0))"

$DeleteAfterDays = "60"

$StaleUsersOU = "blah.com/Maintenance/StaleUsers"

$DateStamp = Get-Date -format yyyyMdd

$DeletedAccountsFile = "C:\scripts\output\DeletedStaleAccounts_$DateStamp.csv"

$noRecentLogonFile = "C:\scripts\output\noRecentLogon_$DateStamp.csv"

$NeverLoggedOnFile = "C:\scripts\output\NeverLoggedOn_$DateStamp.csv"

#Find all accounts that have previously been processe (disabled and moved to new OU) more that $DeleteAfterDays days ago and delete them

$DeletedStaleAccounts = Get-QADUser -Disabled -SearchRoot $StaleUsersOU -IncludedProperties LastLogonTimestamp |

    where {$_.WhenChanged -lt ((get-date).adddays(-$DeleteAfterDays))}

#Find all accounts that have not logged on for at least $InactiveDays days

$noRecentLogon = Get-QADUser  -enabled -SizeLimit 0 -LdapFilter $LdapFilter -IncludedProperties LastLogonTimestamp | 

    where {$_.PasswordNeverExpires -eq $false} |

    sort LastLogonTimestamp 

    

#Find all accounts that where created at least $InactiveDays days ago but have never logged on

$NeverLoggedOn = Get-QADUser  -enabled -SizeLimit 0 -LdapFilter "(!(lastLogonTimestamp=*))" -IncludedProperties LastLogonTimestamp | 

    where {$_.whenCreated -le (get-date).AddDays(-$InactiveDays) -and $_.PasswordNeverExpires -eq $false} |

    sort parentcontainer 

If ($DeletedStaleAccounts -ne $null)

{

    #Export a list of accounts to be deleted

    $DeletedStaleAccounts | Select SAMAccountName, Name, phonenumber, LastLogonTimestamp, PasswordStatus, parentcontainer, WhenChanged  |

        export-CSV -NoTypeInformation $DeletedAccountsFile

    #Delete a bunch of user accounts

    foreach ($user in $DeletedStaleAccounts)

    {

        $DeleteCounter ++

        Write-Host "$DeleteCounter Deleting $user.name"

        ############################################################################

        #Line bellow will change stuff

        ############################################################################

        $user | remove-QADObject -Force

    }

    #Send an email message with an attached list of delete users

    $DELmessage = "The attached list of user stale user accounts have been deleted after being `r`n`r`n"

    $DELmessage += "inactive for $InactiveDays days and then disable for an additional $DeleteAfterDays days. `r`n`r`n"

    $DELmessage += "This script was run by " + $env:username + " on " + $env:COMPUTERNAME + "`r`n`r`n"

    $DELmessage += "ScriptName: $($MyInvocation.MyCommand) `r`n`r`n"

    $DELmessage += "Script path: $(Split-Path -Parent $MyInvocation.MyCommand.Path)"

    Send-MailMessage -From $From -To $To -Bcc $Bcc -SmtpServer $smtpServer `

            -Subject "Stale Users Accounts that have been deleted" `

            -Body $DELmessage -Attachments $DeletedAccountsFile

}

If ($noRecentLogon -ne $null)

{

    $noRecentLogon | Select SAMAccountName, Name, phonenumber, LastLogonTimestamp, PasswordStatus, parentcontainer | 

        export-CSV -NoTypeInformation $noRecentLogonFile

    foreach ($user in $noRecentLogon)

    {

        $NoRecentCounter ++

        Write-Host "$NoRecentCounter Disabling $user.name"

        ############################################################################

        #Line bellow will change stuff

        ############################################################################

        $user | Disable-QADUser | Move-QADObject -NewParentContainer $StaleUsersOU

    }

}

If ($NeverLoggedOn -ne $null)

{

    $NeverLoggedOn | Select SAMAccountName, Name, phonenumber, LastLogonTimestamp, PasswordStatus, parentcontainer | 

        export-CSV -NoTypeInformation $NeverLoggedOnFile

    foreach ($user in $NeverLoggedOn)

    {

        $NeverCounter ++

        Write-Host "$NeverCounter Disabling $user.name"

        ############################################################################

        #Line bellow will change stuff

        ############################################################################

        $user | Disable-QADUser | Move-QADObject -NewParentContainer $StaleUsersOU

    }

}

#Define a list of attachments if they exist and then send an email

if (Test-Path $noRecentLogonFile) {[Array]$Attachments += $noRecentLogonFile}

if (Test-Path $NeverLoggedOnFile) {[Array]$Attachments += $NeverLoggedOnFile}

if ($Attachments) 

{

    #Send an email and attach file

    $message = "The attached lists of accounts have been disabled and moved to a new OU as they have been unused for $InactiveDays days or more. `r`n`r`n"

    $message += "This script is excluding accounts with passwords never expires set `r`n`r`n"

    $message += "Please see the attached files for more details `r`n`r`n"

    $message += "This script was run by " + $env:username + " on " + $env:COMPUTERNAME + "`r`n`r`n"

    $message += "ScriptName: $($MyInvocation.MyCommand) `r`n`r`n"

    $message += "Script path: $(Split-Path -Parent $MyInvocation.MyCommand.Path)"

    Send-MailMessage -From $From -To $To -Bcc $Bcc -SmtpServer $smtpServer `

            -Subject "Disabled User Accounts that have not logged on in the last $InactiveDays days" `

            -Body $message -Attachments $Attachments

}