No Recent Logon

Accounts that have not logged on in the last 20 days

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:\noRecentLogonFile.csv"

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

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

# 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'} `

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

 | sort lastlogon | export-CSV $noRecentLogonFile

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

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

sort parentcontainer | export-CSV -NoTypeInformation $NeverLoggedOnFile

$message = "This script is excluding the following OUs `r`n`r`n"

#$message = $message + "blah.corp/Services `r`n"

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

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

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

-Subject "Users that have not logged on in the last $InactiveDays days" `

-Body $message -Attachments $noRecentLogonFile, $NeverLoggedOnFile

Need to make the same thing over again without quest module using MS activedirectory module

$InactiveDays = "90"

$logonDate = (Get-Date).AddDays(-$InactiveDays)

$InactiveUsers=Get-ADUser -filter { lastLogon -le $logonDate } -Properties Lastlogon, CanonicalName 

$noRecentLogons = $InactiveUsers | where {$_.lastLogon -gt 0} | select SamAccountName, Name, @{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}, CanonicalName | sort lastlogon

$neverLoggedon = $InactiveUsers | where {$_.lastLogon -eq 0} | select SamAccountName, Name, @{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}, CanonicalName | sort lastlogon