1

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
    }
}

}

emcee1342
  • 47
  • 7

2 Answers2

2

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
    }
}
Keith Langmead
  • 785
  • 1
  • 5
  • 16
0

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
}
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
  • I'll give this a try. I'm pretty new in PS (I assume that's obvious), so I don't understand certain aspects of this script, whereas what I wrote came from my understanding of how to accomplish the task. I'll have to study this some and try to understand the syntax. – emcee1342 Jun 08 '23 at 14:08
  • @emcee1342 for the LDAP Filter syntax you can use this: https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx – Santiago Squarzon Jun 08 '23 at 14:10