quarta-feira, 14 de setembro de 2016

Powershell - Find the computer that is locking one account


This script get in each domain controller  information about account lockout.


$DCCounter = 0
$LockedOutStats = @()  

 $User = "TestLock"
 $Domain =  "Contoso.com"


#Get all domain controllers in domain
Write-Verbose "Finding the domain controllers in the domain"
$DomainControllers = Get-ADDomainController -Filter * -Server $Domain

#Get all PDCs in domain
 $PDCEmulator = ($DomainControllers | Where-Object {$_.OperationMasterRoles -contains "PDCEmulator"})
     
 Foreach($DC in $DomainControllers) {
   $DCCounter++
 
  Try {
          $UserInfo = Get-ADUser -Identity $User  -Server $DC.Hostname -Properties AccountLockoutTime,LastBadPasswordAttempt,BadPwdCount,LockedOut -ErrorAction Stop
        }
    Catch {
            Write-Warning $_
            Continue
          }
    If($UserInfo.LastBadPasswordAttempt) {  
      $LockedOutStats += New-Object -TypeName PSObject -Property @{
         Name                   = $UserInfo.SamAccountName
         SID                    = $UserInfo.SID.Value
         LockedOut              = $UserInfo.LockedOut
         BadPwdCount            = $UserInfo.BadPwdCount
         BadPasswordTime        = $UserInfo.BadPasswordTime          
         DomainController       = $DC.Hostname
         AccountLockoutTime     = $UserInfo.AccountLockoutTime
         LastBadPasswordAttempt = ($UserInfo.LastBadPasswordAttempt).ToLocalTime()
      }        
    }
 }

 $LockedOutStats | Format-Table -Property Name,LockedOut,DomainController,BadPwdCount,AccountLockoutTime,LastBadPasswordAttempt -AutoSize

 #Get User Info
 Try {
       Write-Verbose "Querying event log on $($PDCEmulator.HostName)"
       $LockedOutEvents = Get-WinEvent -ComputerName $PDCEmulator.HostName -FilterHashtable @{LogName='Security';Id=4740} -ErrorAction Stop | Sort-Object -Property TimeCreated -Descending
      }
 Catch {        
         Write-Warning $_
         Continue
       }  
                               
 Foreach($Event in $LockedOutEvents) {          
   If($Event | Where {$_.Properties[2].value -match $UserInfo.SID.Value}) {
           
         $Event | Select-Object -Property @(
            @{Label = 'User';               Expression = {$_.Properties[0].Value}}
            @{Label = 'DomainController';   Expression = {$_.MachineName}}
            @{Label = 'EventId';            Expression = {$_.Id}}
            @{Label = 'LockedOutTimeStamp'; Expression = {$_.TimeCreated}}
            @{Label = 'Message';            Expression = {$_.Message -split "`r" | Select -First 1}}
            @{Label = 'LockedOutLocation';  Expression = {$_.Properties[1].Value}}
          )                                      
   }
           
 }
     

Nenhum comentário:

Postar um comentário