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
Where-Object
condition after fetching the data. – Ansgar WiechersGet-ADUser -SearchBase $OU -SearchScope OneLevel | where { $_.extensionAttribute12 -notlike "*" .....other properties} | Select-Object Name, samAccountName, extensionAttribute12, whenCreated, enabled, employeeT
– TheGameiswar