3
votes

What I am trying to do:
Return a list of AD users filtered by the date stored in an AD attribute using PowerShell.

The problem
The date I want to filter on is stored in an AD attribute with a string data type, specifically extensionAttribute12. This is non-negotiable with the people I am writing the script for.

I'm having trouble getting the syntax right in my filter to cast that string to a date before the comparison.

Here's my non-working code:

Import-Module ActiveDirectory

$CurrentDate = Get-Date
$CurrentDate = $CurrentDate.ToString('MM-dd-yyyy')
$OU = "OU=PIV_Users,OU=FakeOU,DC=fake,DC=com"
$30Days = (Get-Date).AddDays(-30)

Get-ADUser -SearchBase $OU -SearchScope OneLevel -Filter {(extensionAttribute12 -notlike "*" -or extensionAttribute12 -le $30days) -and (enabled -eq $true) -and (whencreated -lt $30Days)} -Properties * |
    Select-Object Name, samAccountName, extensionAttribute12, whenCreated, enabled, employeeType

This is the error:

Get-ADUser : Invalid type 'System.DateTime'.
Parameter name: extensionAttribute12
At line:9 char:1

I tried adding a cast as follows

... -or **[DateTime]extensionAttribute12** -le $30days) ...

Which gave me this error:

Get-ADUser : Error parsing query: '(extensionAttribute12 -notlike "*" -or [DateTime]extensionAttribute12 -le $30days) -and (enabled -eq $true) -and (whencreated -lt $30Days)'
Error Message: 'syntax error' at position: '40'.
At line:9 char:1

1
I don't think that's possible in an AD search string. You need to do it in a Where-Object condition after fetching the data.Ansgar Wiechers
Can you provide an example in an answer so I can upvote it?JohnFx
Can't test it,since i dont have active directory module on my local machine, can you try below Get-ADUser -SearchBase $OU -SearchScope OneLevel | where { $_.extensionAttribute12 -notlike "*" .....other properties} | Select-Object Name, samAccountName, extensionAttribute12, whenCreated, enabled, employeeTTheGameiswar
That worked. Please enter it as an answer so I can upvote and accept it. You deserve the unicorn tears!JohnFx

1 Answers

3
votes

To my knowledge it's not possible to cast attributes to a different type in an AD search string. Despite the scriptblock-like notation the argument to the parameter -Filter is essentially a query string.

What you can do is do the filtering via Where-Object after fetching the objects. That's not optimal (because your AD query will return more objects than it needs to), but in this case I don't see another way. Make sure, however, that you only move those parts of the filter to the Where-Object that won't work otherwise, so that Where-Object doesn't need to process all user objects.

Get-ADUser-Filter {extensionAttribute12 -notlike '*' -and enabled -eq $true -and whencreated -lt $30Days} ... |
    Where-Object { [DateTime]extensionAttribute12 -le $30days } |
    ...