Reputation: 11
I am trying to use Powershell to pull All members of a Active Directory group who are currently active (both account is enabled and not expired).
I thought what I had worked but I noticed that some users that have expiration dates in the future were ignored. I tried added () around the AccountExpirationDate check because if they don't have a expiration date or if that date is in the future they are currently active. When I use the () I get no results.
Does anyone have any suggestions?
Get-ADGroupMember 'Employees' |
Get-ADUser -Properties Enabled, EmailAddress,AccountExpirationDate |
Where-Object {$_.mail -like '@domain.com' -and $_.AccountExpirationDate -gt (Get-Date) -or $_.AccountExpirationDate -eq $null -and $_.Enabled -eq $True } |
Select-Object GivenName,Surname, EmailAddress,AccountExpirationDate|
#Select-Object -expand EmailAddress
Export-csv -path "export.csv" -NoTypeInformation
User must be a member of x group. Users account must be active users account cannot be expired List their First Name, Last Name and Email address
Upvotes: 1
Views: 2216
Reputation: 60045
Max has provided some key pointers in a comment, here is how the complete LDAP Filter would look like:
$date = [datetime]::Now.ToFileTimeUtc()
$group = (Get-ADGroup Employees).DistinguishedName
$filter = -join @(
"(&" # AND (all conditions must be met)
"(!userAccountControl:1.2.840.113556.1.4.803:=2)" # Enabled Object
"(mail=*@domain.com)" # mail ends with `@domain.com`
"(memberOf=$group)" # object is a member of `$group`
"(|" # OR (one of the conditions must be met)
"(accountExpires>=$date)" # account expiration is greater than Now (UTC)
"(accountExpires=0)" # account never expires
"(accountExpires=9223372036854775807)" # account never expires
")" # closing OR clause
")" # closing AND clause
)
Get-ADUser -LDAPFilter $filter -Properties EmailAddress, AccountExpirationDate |
Select-Object GivenName, Surname, EmailAddress, AccountExpirationDate |
Export-Csv -Path "export.csv" -NoTypeInformation
Upvotes: 0