Get a list of users who are Domain Admins and have not logged in the past 30 days?

How can I get a list of users from AD who are Domain Admins and have not logged in the past 30 days?


user360071, here is a PowerShell script that will do what you want.

Import-Module ActiveDirectory
$Age = 30
$When = ((Get-Date).AddDays(-$Age)).Date
$Members = (Get-ADGroupMember -Identity "Domain Admins" -Recursive).DistinguishedName
Foreach ($Member in $Members) {
Get-ADUser -Identity $Member -Property LastLogonDate | Where LastLogonDate -lt $When | Select SamAccountName,UserPrincipalName,LastLogonDate | Export-CSV -Path $env:USERPROFILE\Desktop\users.csv -NoTypeInformation -Append
}

You can make a small change so you can pick how long you want to look for an account that has not logged in. Here is the changed version.

Import-Module ActiveDirectory
$Age = Read-Host "Accounts that have not been logged into in the last how many days should be shown?"
$When = ((Get-Date).AddDays(-$Age)).Date
$Members = (Get-ADGroupMember -Identity "Domain Admins" -Recursive).DistinguishedName
Foreach ($Member in $Members) {
Get-ADUser -Identity $Member -Property LastLogonDate | Where LastLogonDate -lt $When | Select SamAccountName,UserPrincipalName,LastLogonDate | Export-CSV -Path $env:USERPROFILE\Desktop\users.csv -NoTypeInformation -Append
}

Updated Answer

Hello user360071. When you want to add another request to your question or need to clarify what you are trying to ask you can edit your question and save the changes.

In your addition you added that you want to be able to save the results to an Excel file.

You tried >> users.csv but the Excel file is empty. In PowerShell what you want to do is | Export-CSV users.csv. The scripts have been updated with this.