关于活动目录:在PowerShell中调用Get-ADUser时,如何在过滤条件下转换AD属性?

How can I cast an AD Attribute in a filter condition when calling Get-ADUser in PowerShell?

我正在尝试做的是:
使用PowerShell返回按存储在AD属性中的日期过滤的AD用户列表。

问题
我要过滤的日期存储在具有字符串数据类型(特别是extensionAttribute12)的AD属性中。 这与我为之编写脚本的人员无法商议。

我在将过滤器的语法正确转换为比较之前的日期时遇到麻烦。

这是我的无效代码:

1
2
3
4
5
6
7
8
9
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

这是错误:

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

我尝试如下添加演员表

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

这给了我这个错误:

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


据我所知,不可能在AD搜索字符串中将属性强制转换为其他类型。 尽管使用类似于脚本块的表示法,但参数-Filter的参数实际上是查询字符串。

您可以做的是在获取对象之后通过Where-Object进行过滤。 这不是最佳选择(因为您的AD查询将返回比所需数量更多的对象),但是在这种情况下,我看不到其他方法。 但是,请确保仅将过滤器的那些部分移到Where-Object上,否则这些部分将无法正常工作,从而使Where-Object不需要处理所有用户对象。

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