Hi everyone can someone help me with the following script. the next things must be added:
- Last logon date of the user
- Export to excel .csv
Much appreciated
$dcs = Get-ADDomainController -Filter { Name -like "*" }
# create hashtable to keep track of latest timestamps per user
$userLastLogonTable = @{}
foreach($dc in $dcs){
# fetch all users from each DC
Get-ADUser -Filter * -Properties LastLogonDate -Server $dc | ForEach-Object {
# Only add new timestamps to table if we either haven't seen the username before, or if the timestamp is newer than the current
if(-not $userLastLogonTable.Contains($_.SAMAccountName) -or $userLastLogonTable[$_.SAMAccountName].LastLogonDate -lt $_.LastLogonDate){
$userLastLogonTable[$_.SAMAccountName] = [pscustomobject]@{
LastLogonDate = $_.LastLogonDate
LogonServer = $dc.Name
}
}
}
}
# Now that we have a complete table of all users and their last logon timestamp,
# we can then easily identify usernames that have no recent logons
$staleUserNames = $userLastLogonTable.PSBase.Keys |Where-Object { $userLastLogonTable[$_].LastLogonDate -le (Get-Date).AddDays(-30) }
CodePudding user response:
Add the samaccountname value to the custom object:
$userLastLogonTable[$_.SAMAccountName] = [pscustomobject]@{
SAMAccountName = $_.SAMAccountName
LastLogonDate = $_.LastLogonDate
LogonServer = $dc.Name
}
Then filter on the values of the hashtable rather than the keys:
$staleUserEntries = $userLastLogonTable.PSBase.Values |Where-Object { $_.LastLogonDate -le (Get-Date).AddDays(-30) }
At which point you can export to CSV with Export-Csv
:
$staleUserEntries |Select SAMAccountName,LastLogonDate |Export-Csv path\to\output.csv -NoTypeInformation