Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # https://www.reddit.com/r/PowerShell/comments/4mtg6a/finding_disabled_ad_users_in_the_past_30_days_and/
- param (
- [parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, mandatory=$false)]
- [string]$SearchBase,
- [parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, mandatory=$false)]
- [int]$Days
- )
- Import-Module ActiveDirectory
- if ($searchBase -eq '') {
- $searchBase = (Get-ADRootDSE).defaultNamingContext;
- }
- if ($Days -lt 1) {
- $Days = 1
- }
- $Days *= -30
- $users = Get-ADObject -Filter { objectCategory -eq 'Person' -and (userAccountControl -bor 2) } -SearchBase $SearchBase -Properties sAMAccountName
- $searchFrom = (Get-Date 0:0).AddDays($Days)
- $results = New-Object System.Collections.ArrayList
- $index = 0
- $total = $users.Count
- $starttime = $lasttime = Get-Date
- foreach ($userEntry in $users) {
- $index++
- $currtime = (Get-Date) - $starttime
- $avg = $currtime.TotalSeconds / $index
- $last = ((Get-Date) - $lasttime).TotalSeconds
- $left = $total - $index
- $WrPrgParam = @{
- Activity = (
- "Getting user info $(Get-Date -f s)",
- "Total: $($currtime -replace '\..*')",
- "Avg: $('{0:N2}' -f $avg)",
- "Last: $('{0:N2}' -f $last)",
- "ETA: $('{0:N2}' -f ($avg * $left / 60))",
- "min ($([string](Get-Date).AddSeconds($avg * $left) -replace '^.* '))"
- ) -join ' '
- Status = "$index of $total ($left left) [$('{0:N2}' -f ($index / $total * 100))%]"
- CurrentOperation = "User: $userEntry"
- PercentComplete = $index / $total * 100
- }
- Write-Progress @WrPrgParam
- $lasttime = Get-Date
- $user = Get-ADObject -Filter { sAMAccountName -eq $userEntry.sAMAccountName } -Properties sAMAccountName, userAccountControl, mail, 'msDS-ReplAttributeMetaData'
- $repData = $repData = [xml]('<root>' + $user.'msDS-ReplAttributeMetaData' + '</root>').Replace([char]0, ' ')
- foreach ($attribute in $repData.root.DS_REPL_ATTR_META_DATA) {
- if ($attribute.pszAttributeName -eq 'userAccountControl') {
- $changedDate = Get-Date $attribute.ftimeLastOriginatingChange
- if ($changedDate -gt $searchFrom) {
- $obj = [pscustomobject]@{
- Mail = $user.mail
- sAMAccountName = $user.samaccountname
- UserAccountControl = $user.useraccountcontrol
- Changed = $changedDate
- }
- Write-Output $obj
- $null = $results.Add($obj)
- }
- }
- }
- }
- $smartHost = 'smtp.server.com'
- $mailSubject = 'PowerShell Disabled Users in Past 30 Days'
- $mailBody = $results | Format-Table -AutoSize | Out-String
- Send-MailMessage -Subject $mailSubject -From $sendFrom -To $sendTo -SmtpServer $smartHost -body $mailBody
Add Comment
Please, Sign In to add comment