powershell filter get-aduser

204 Views Asked by At

I'm trying to write a tiny script to run through our organization's OUs in AD and return users whose password expires in two weeks or less. One issue I ran into is service accounts in the primary OUs, so I'm trying to exclude accounts whose email address contains "noreply", but I continue to get the noreply accounts in my return. Any thoughts?

foreach($OU in $OUs) {
$Users = Get-ADUser -SearchBase $OU -filter * -properties *
foreach($User in $Users) {
    if(($User.PasswordLastSet -lt $CutOffDate) -and ($User.EmailAdress -notcontains 'noreply*')) {
        write-host $User.EmailAddress
    }
}

}

2

There are 2 best solutions below

0
Keith Langmead On BEST ANSWER

To achieve that you want to use -notlike rather than -notcontains so this should do what you're after.

foreach($OU in $OUs) {
$Users = Get-ADUser -SearchBase $OU -filter * -properties *
foreach($User in $Users) {
    if(($User.PasswordLastSet -lt $CutOffDate) -and ($User.EmailAdress -notlike 'noreply*')) {
        write-host $User.EmailAddress
    }
}
2
Santiago Squarzon On

Your query can be reduced to this if you leverage Active Directory filtering capabilities, this would be much more efficient than doing the filtering with PowerShell.

$limit = [datetime]::UtcNow.AddDays(-14).ToFileTimeUtc() # 2 weeks limit
$getADUserSplat = @{
    # `mail` attribute not like `noreply` AND
    # `pwdLastSet` is lower than 14 days ago
    LDAPFilter = "(&(!mail=noreply*)(!pwdLastSet>=$limit))"
    Properties = 'mail', 'passwordLastSet'
}
$users = Get-ADUser @getADUserSplat

If you want to run the query per $ou the code would become:

$limit = [datetime]::UtcNow.AddDays(-14).ToFileTimeUtc() # 2 weeks limit
$getADUserSplat = @{
    LDAPFilter = "(&(!mail=noreply*)(!pwdLastSet>=$limit))"
    Properties = 'mail', 'passwordLastSet'
}

$users = foreach($ou in $ous) {
    Get-ADUser @getADUserSplat -SearchBase $ou
}