Using Powershell to Trace the Source of Account Lockouts in Active Directory

How to: track the source of user account lockout using Powershell

In my last post about how to Find the source of Account Lockouts in Active Directory I showed a way to filter the event viewer security log with a nifty XML query.

In this post I recomposed (Source:Ian Farr) a Powershell script which will ask for the locked user account name and then will scan the active directory DCs security log for relevant events and will present the user lock time and source of the lock out like so:

locked user powershell script

Make sure you have the active directory module loaded on the machine you run the script from: Import-Module ActiveDirectory

You can add the import-module command to the top of the script if you like.

The script:

$ErrorActionPreference = "SilentlyContinue"
Clear-Host

$User = Read-Host -Prompt "Please enter a user name"

#Locate the PDC
$PDC = (Get-ADDomainController -Discover -Service PrimaryDC).Name
#Locate all DCs
$DCs = (Get-ADDomainController -Filter *).Name #| Select-Object name

foreach ($DC in $DCs) {
Write-Host -ForegroundColor Green "Checking events on $dc for User: $user"
    if ($DC -eq $PDC) {
        Write-Host -ForegroundColor Green "$DC is the PDC"
        }
    Get-WinEvent -ComputerName $DC -Logname Security -FilterXPath "*[System[EventID=4740 or EventID=4625 or EventID=4770 or EventID=4771 and TimeCreated[timediff(@SystemTime) <= 3600000]] and EventData[Data[@Name='TargetUserName']='$User']]" | Select-Object TimeCreated,@{Name='User Name';Expression={$_.Properties[0].Value}},@{Name='Source Host';Expression={$_.Properties[1].Value}} -ErrorAction SilentlyContinue
    }

This script scans ALL Domain Controllers and not just the PDC as most people do. I found that sometimes a lockout event will appear in a different DC server, so to make sure you dont miss anything, its better in my opinion to scan all domain controllers and wait the extra time for the script to finish. However, in most cases lockout events will appear on the PDC server.

After you have found the source of user lockout, go to each PC and disconnect the session or look for running scheduled tasks or scripts under this user context.  Rebooting the locking PC if possible, is also a good practice.

Here is another script contributed by Alexandre Almeida on the same topic.

#script written by Alexandre Almeida

# for get user Account Lockout Host name

$username = Read-Host "Please Enter the Locked User Name: "
 
        $DCCounter = 0  
        $LockedOutStats = @()    
                 
        Try 
        { 
            Import-Module ActiveDirectory -ErrorAction Stop 
        } 
        Catch 
        { 
           Write-Warning $_ 
           Break 
        } 
         
        #Get all domain controllers in domain 
        $DomainControllers = Get-ADDomainController -Filter * 
        $PDCEmulator = ($DomainControllers | Where-Object {$_.OperationMasterRoles -contains "PDCEmulator"}) 
         
        Write-Verbose "Finding the domain controllers in the domain" 
        Foreach($DC in $DomainControllers) 
        { 
            # $DCCounter++ 
            # Write-Progress -Activity "Contacting DCs for lockout info" -Status "Querying $($DC.Hostname)" -PercentComplete (($DCCounter/$DomainControllers.Count) * 100) 
      Write-Verbose "Finding the Which domain controllers Authenticate the Password"
            Try 
            { 
                $UserInfo = Get-ADUser -Identity $username  -Server $DC.Hostname -Properties LastLogonDate -ErrorAction Stop 
      Write-Verbose "Bad Password Attempt count collected"
            } 
            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 
                        LastLogonDate = ($UserInfo.LastLogonDate).ToLocalTime() 
                    }           
            }#end if 
        }#end foreach DCs 
        $LockedOutStats | Format-Table -Property Name,LockedOut,DomainController,BadPwdCount,AccountLockoutTime,LastBadPasswordAttempt -AutoSize 
 
        #Get User Info 
        Try 
        {   
           Write-Verbose "Querying event log on $($PDCEmulator.HostName)" 
     Write-Verbose "Collecting Event Log"
           $LockedOutEvents = Get-WinEvent -ComputerName $PDCEmulator.HostName -FilterHashtable @{LogName='Security';Id=4740} -ErrorAction Stop | Sort-Object -Property TimeCreated -Descending 
        } 
        Catch  
        {           
           Write-Warning $_ 
           Continue 
        }#end catch      
                                  
        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}}
             ) 
      Write-host $_.MachineName
                                                 
            }#end ifevent 
             
       }#end foreach lockedout event
  Write-Verbose "Collected Details Update in the Text File. Please find the Text file for More Details"

echo "Cache Profile Removal Steps
1) Open Control Panel > Credential Manager > Remove all Saved Password.
2) Remove passwords by clicking on Start => Run => type (rundll32.exe keymgr.dll KRShowKeyMgr) without quotes and then delete the Domain-related passwords;
3) Remove passwords in Internet Explorer => Tools => Internet Options =>Content => Personal Information => Auto Complete => Clear Passwords;
4) Delete cookies in Internet Explorer => Tools => Internet Options =>General;
5) Disconnect (note the path before disconnecting) all networks drives, reboot, then map them again;
6) Start -> run ->type control userpasswords2 without quotes and go to advanced -> Manage passwords and remove all the stored passwords.
7) Reconfigure Your mobile Setting if your Active sync enabled.
8) Check if any saved or scheduled task is configured for user account

Microsoft Kwoledge Bytes Link for Cache profile Removal Steps:

https://social.technet.microsoft.com/Forums/windows/en-US/ced8eab6-87e2-4d20-9d18-7aaf5e9713a3/windows-7-clear-cached-credentials"

 

Find the source of Account Lockouts in Active Directory

How to: Find the source of Account Lockouts in Active Directory

It is a very common problem in Active Directory when Users change their password in a domain environment, they might get locked out repeatedly and it can be a frustrating process to identify the source of the lockout.

Try the following steps to track the locked out user and also find the source of AD account lockouts. This procedure assume that you know the username which is locked out.

I recommend doing this procedure on ALL your Domain Controllers, not only your PDC Server, just to be sure you didn’t miss a lockout event.

  • You need to create a filter on the security log on your DCs. We will use a very handy XML query for that. These specific events are good for a 2008 R2 Domain Controller. You can easily change the event numbers for other Windows server editions.
  • To start, Right click security log and select ‘Filter current log’

Filter security log

  • Select the XML tab and tick the ‘Edit query manually‘ radio button.
  • Copy the following query to the XML window. You need to change the UserName and Domain\UserName  values respectively for your specific domain and user.
<QueryList>
  <Query Id="0" Path="Security">
    <Select Path="Security">
            *[System[(EventID=4771 or EventID=4770 or EventID=4625 or EventID=6274)]]
            and
            *[EventData[Data and (Data='UserName' or Data='Domain\UserName')]]
          </Select>
  </Query>
</QueryList>

Filter locked user XML

 

  • Click OK to confirm the filter.
  • Now inside the events that were discovered in the security log, refer to the client address and client port to continue your investigation on the source of the lockout. in the below example you can see the source of lockout in the client address and client port lines.

event id 4771

Disconnect the user from the computers he is still trying to establish connections from.

You will receive all relevant events for the lockout for the specified user.

Power off the virtual machine in an ESXi host

Unable to power off the virtual machine in an ESXi host

Source: https://kb.vmware.com/s/article/1014165

Using the ESXi command-line utility vim-cmd to power off the virtual machine

  1. SSH into your ESXi server
  2. Get a list of all registered virtual machines, identified by their VMID, Display Name, and path to the .vmx configuration file by running this command: vim-cmd vmsvc/getallvms
    vim-cmd vmsvc/getallvms

  3. Get the current state of a virtual machine by running this command:
    vim-cmd vmsvc/power.getstate VMID

  4. Shutdown the virtual machine using the VMID found in Step 2 and run this command:
    vim-cmd vmsvc/power.shutdown VMID

  5. If the virtual machine fails to shut down, run this command:
    vim-cmd vmsvc/power.off VMID

Using the ESXi esxcli command to power off a virtual machine

The esxcli command can be used locally or remotely to power off a virtual machine running on ESXi 5.x or later.

  1. Open a console session where the esxcli tool is available, Isimply SSH to your ESXi machine.
  2. Get a list of running virtual machines, identified by World ID, UUID, Display Name, and path to the .vmx configuration file by running this command:
    esxcli vm process list
  3. Power off the virtual machine from the list by running this command:
    esxcli vm process kill --type= [soft,hard,force] --world-id= WorldNumber

    Notes:

    • Three power-off methods are available. Soft is the most graceful, hard performs an immediate shutdown, and force should be used as a last resort.
    • alternate power off command syntax is: esxcli vm process kill -t [ soft,hard,force] -w WorldNumber
  4. Repeat Step 2 and validate that the virtual machine is no longer running.

 

 

 

 

SCCM Report – Count All Computers by Model

How to create a MS Configuration manager report that will Count All Computers for each Model

This guide will show you how to create a report in Microsoft System Center Configuration Manager 2012(R2) / Current branch 1702. In this example we will be creating a report which lists all system models and displays a count of each model.

SCCM 2012 (last checked on build 1702) does not have a prebuilt report that will simply return a list of all the distinct manufacturer/model numbers for all the computers in the environment and a count of each type.

This SCCM report will retrieve all the computer models  in one column and count of each model in the the adjacent column:

SELECT        Model0 AS Model, COUNT(*) AS Count, Domain0

FROM            dbo.v_GS_COMPUTER_SYSTEM

GROUP BY Model0, Domain0

Output of the report:

sccm report Count Computer by Model

If you happen to have Lenovo models in your organisation, you will find it useful to translate the Lenovo’s models to real model names. The following query will do that:

SELECT COUNT(*) No_Of_Items, 

CASE WHEN MODEL0 IN('10AXS2PX00') THEN 'Lenovo M73'

WHEN MODEL0 IN('10ahs00d00') THEN 'Lenovo M83'

WHEN MODEL0 IN('10FCS06W00','10FCS0W500','10FHS00D00','10FHS07Q00','10FHS0AK00') THEN 'Lenovo M900'

WHEN MODEL0 IN('10MKS03H00','10MKS04G00','10MKS04H00') THEN 'Lenovo M910s '

WHEN MODEL0 IN('10A7A00P00','10A7S00P00','10A7A00L00','10A7CTO','10A7S00D00',

'10A7S00S00','10A7S02700','10A7S02800','10A7S02D00','10A8A02H0C',

'10A8S2E100','10A9003PIV','10A9S02X00') THEN 'Lenovo M93p'

WHEN MODEL0 IN('SLIC-BPC') THEN 'HP Compaq Elite 8300 BPC'

WHEN MODEL0 = 'To be filled by O.E.M.' THEN 'WeyTech'

ELSE Model0 END [Model]

FROM v_GS_COMPUTER_SYSTEM


WHERE model0 like '%hp%' or model0 like '%think%' or model0 like '%10%' or model0 like '%O.E.M%' or model0 like '%SLIC-BPC%'

GROUP BY CASE WHEN MODEL0 IN('10AXS2PX00') THEN 'Lenovo M73'

WHEN MODEL0 IN('10ahs00d00') THEN 'Lenovo M83'

WHEN MODEL0 IN('10FCS06W00','10FCS0W500','10FHS00D00','10FHS07Q00','10FHS0AK00') THEN 'Lenovo M900'

WHEN MODEL0 IN('10MKS03H00','10MKS04G00','10MKS04H00') THEN 'Lenovo M910s '

WHEN MODEL0 IN('10A7A00P00','10A7S00P00','10A7A00L00', '10A7CTO','10A7S00D00',

'10A7S00S00','10A7S02700','10A7S02800',  '10A7S02D00','10A8A02H0C',

'10A8S2E100','10A9003PIV','10A9S02X00') THEN 'Lenovo M93p'

WHEN MODEL0 IN('SLIC-BPC') THEN 'HP Compaq Elite 8300 BPC'

WHEN MODEL0 = 'To be filled by O.E.M.' THEN 'WeyTech'

ELSE Model0 END


ORDER BY No_Of_Items DESC, model

 Download the .rdl file for this report from here: All Computers in specific Collection

How to Ping a List of Computers

Many times It happens that we need to check if a list of computers is active, so how do you ping multiple computers at once?

Use this Powershell script to test connectivity to your list of computers. it will produce two lists of Bad (unresponsive) and Good(Responsive) computers.

You need to change “D:\scripts\list.txt” to the path where your saved your computers list file(.txt).

Also, you can un-comment  #Write-Host $name… to view the list of computers with different colors

$Mylist = Get-Content D:\scripts\list.txt #this is where you put your list of computers
Clear-Host
[System.Collections.ArrayList]$GoodArrayList = @()
[System.Collections.ArrayList]$BadArrayList = @()
 

foreach ($name in $Mylist){
  if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
    #Write-Host $name -ForegroundColor Cyan
    $GoodArrayList.Add($name)
  }
 
else{
    #Write-Host $name "down" -ForegroundColor Red
    $BAdArrayList.Add($name)
  }
}
Write-Host -ForegroundColor Cyan "Good Computers :)"
$GoodArrayList
Write-Host -ForegroundColor Red "Bad Computers :("
$BadArrayList

How to run python script on notepad++

How to  Configure Notepad++ to run a python script via python IDLE

If you are learning python and want to use notepad++ as a free as well as simple and easy to use editor, follow these simple steps:

Install python (2.7.x)

First thing: Download the python 2.7.x (current is 2.7.13) windows installer from http://www.python.org/download/ using the default settings. It should install python in the folder: C:\Python27. You can use a different version of python, just substitute out the version number wherever you see 27. Continue reading How to run python script on notepad++

0x8007052e error in task scheduler

0x8007052e error in task scheduler

Symptom: You get 0x8007052e error when trying to run scheduled task from task scheduler.

There can be several causes for this including authentication problem like bad password.

But I did not easily find documented online records for this error being caused by a group policy, so I think this post might help you – system admins.

Continue reading 0x8007052e error in task scheduler

Installing SCOM 2012 agent on a workgroup or DMZ machine using Certificate

How to Install SCOM Agent on an Un-trusted machine

In order for SCOM to communicate with an un-trusted machine like in a WorkGroup / DMZ / different forest, you will have to import a certificate so that SCOM will trust the foreign machine and will be able to communicate with it. The most common example is a SCOM Gateway.
This topic is a bit complicated but if you use a guide like this you should be OK.

I added the files that you will need as well so you dont have to copy-paste it. Additional files: REQconfig.inf certreq

First thing you will need is an inf file that contains the request.

Continue reading Installing SCOM 2012 agent on a workgroup or DMZ machine using Certificate

Memory leak

Memory leak – when the Available MegaBytes (memory\% available Mbytes) for the system has exceeded the threshold, system performance may be significantly diminish, this results in low OS and applications performance. End users will usually complain about slow computer performance and you probably get a help-desk call like: ‘My computer is running slow’, or server is running slow.

Memory leaks can be caused by:

  • Too many applications running simultaneously on the computer.
  • An application may be leaking memory over time.

To view the history for the memory\% available Mbytes, start memory available Mbytes in performance monitor or event task manager\performance.

Continue reading Memory leak

Public Desktop Icons are Deleted After Logon in Windows 7

I think I that a suitable name for  this post might be ‘The case of the missing desktop shortcuts’.  I spent nearly an hour or more resolving the so it will be the right thing to share it with you.

The Problem

In Windows 7,  Users can’t view objects and icons published on “C:\Users\Public\Desktop” .

Users cannot read data from “C:\Users\Public\Desktop”.

You suspect that a GPO – Group policy object, prohibit users from viewing icons on “C:\Users\Public\Desktop” folder.

Continue reading Public Desktop Icons are Deleted After Logon in Windows 7

System Administrators Tricks