Find users from AD OU and for each user find Logon and Logout Times in Eventlogs

386 Views Asked by At

I am searching a script which takes all users from an OU of Active Directory as

$searchBase = "ou=users,ou=ABC,OU=Gardezi,DC=Gardezi,dc=com"
$searchTree = "ou=XXDepartment,", "ou=CSDepartment,"        
foreach ($ou in $searchTree) {
  write-host "searching in OU: $ou $searchBase"
  $name = $ou
  $name = $name.subString($name.IndexOf("=")+1,$name.Indexof(",")-3)
}

and for each user find the logon and logoff times through EventLog on 2 of my computers during last week. Logon requirement should meet the EventId=4624 and logon type=2 0r 10 as

(($_.InstanceId -eq 4624) -and ($_.Message -match "Logon Type:2")) -or
(($_.InstanceId -eq 4624) -and ($_.Message -match "Logon Type:10")

for say 7 days.

Can any one please complete this for me?

1

There are 1 best solutions below

4
Ansgar Wiechers On

When in doubt, read the documentation. The Get-EventLog cmdlet has a parameter -ComputerName that accepts a list of computer names. The time range can be restricted via the -Before and -After parameters.

$username = 'foo'
$hosts    = 'HostA', 'HostB', ...
$age      = (Get-Date).AddDays(-7)

Get-EventLog -Log Security -Computer $hosts -InstanceId 4624 -After $age | ? {
  $_.Message -match "account name:\s+$username\s" -and
  $_.Message -match 'logon type:\s+(2|10)\s'
}