I had a simple request the other day that I wanted to log on this site since I vaguely remember having to do it before.
A quick background – Our company has merged with another company which means we will be busy in the coming months with implementing a new domain. One thing we need to do is create new accounts on the new domain for all the users in each of the existing domains. Since we have thousands of user accounts (some internal and some external or contractors) we needed a way to find out which of these accounts have been used in an X number of days.
The easiest and quickest way I could think to do this is to create a PowerShell Script to query the AD and get the Last Login variable from the account. Problem that I found was that the AD account will record the Login with the Domain Controller that it logs in to. If you have more than one domain controller (you have more than one right!!??) the domain controllers don’t sync that login info. So below is the code used to query the domain controllers and get the last logon info from each.
Disclaimer – I didn’t not write this code but found it after sorting through several google searches. If you wrote this .. thank you. I am putting it here for my own reference so next time I am asked to get the information I will know right where to look.
[code]
$datetime = Get-Date -Format “yyyyMMddhhmmss”;
# Create and Add Headers to CSV
Add-Content “c:tempLastLogin – $datetime.csv” “User,Last Logon”;
Get-QADUser | ForEach-Object {
Write-Host $_.Name
Write-Host $_.LastLogon
$user = $_.Name
$time = $_.LastLogon
$sc = [char]34
# Add Data to CSV
Add-Content “c:tempLastLogin – $datetime.csv” “$sc$user$sc,$sc$time$sc”
}
[/code]
Steps are to:
- Create a file with the above code and save as LastLogin.ps1
- Run the file using PowerShell (.LastLogin.PS1)
- Open and read “LastLogin – DateTime.csv”
I also combined this with a PowerShell Script to create a SharePoint List but that is a different post on a different Blog (at a different time)