根据自定义属性值删除 90 天后禁用的帐户

Delete the disabled accounts since 90 days based on custom attribute value

我自动移动 OU 中所有禁用广告的帐户,并使用此脚本在 extensionattribute4 中添加停用日期:

import-module activedirectory
$timer = (Get-Date)
$TargetOU = "OU=Disabled Accounts,DC=domain,DC=lan"
$DisabledAccounts = get-aduser -filter { enabled -eq $false } -SearchBase "OU=Test,OU=EMEA,DC=domain,DC=lan"

ForEach ($account in $DisabledAccounts) {
set-aduser -Identity $account.distinguishedName -add @{extensionAttribute4="$timer"}
}

ForEach ($account in $DisabledAccounts) {
Move-ADObject -Identity $account.distinguishedName -TargetPath $TargetOU

但是,当我想使用脚本删除广告禁用帐户时,引用日期为 extensionattribute4 少于 90 天:

import-module activedirectory
$DaysInactive = 90
$time = (Get-Date).Adddays(-($DaysInactive))
$DisabledAccounts = get-aduser -filter { extensionattribute4 -lt $time -and enabled -eq $false } -SearchBase "OU=Disabled Accounts,DC=domain,DC=lan"

ForEach ($account in $DisabledAccounts) {
Remove-ADObject -Identity $account.distinguishedName
}

我有一个错误:

get-aduser : Invalid type 'System.DateTime'.
Parameter name: extensionattribute4
At C:\removedisabledadaccounts.ps1:4 char:21
+ $DisabledAccounts = get-aduser -filter { extensionattribute4 -lt $time -and enab ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-ADUser], ArgumentException
    + FullyQualifiedErrorId : Invalid type 'System.DateTime'.
Parameter name: extensionattribute4,Microsoft.ActiveDirectory.Management.Commands.GetADUser

该错误表明您正在尝试执行该属性不接受的操作。当您在之前的操作中填充该字段时,您将日期转换为带有 @{extensionAttribute4="$timer"} 的字符串。我无法想象这些属性无论如何都存储为字符串以外的任何东西。事实上,尝试存储日期对象以类似的失败告终。

感谢使用 -Filter,但我确信这超出了 -Filter/-LDAPFilter,因此您只需要进行一些 post 处理。

Get-ADUser -Filter {enabled -eq $false} -SearchBase "OU=Disabled Accounts,DC=domain,DC=lan" -Properties extensionattribute4 | 
    Where-Object{$time -ge $_.extensionattribute4}

由于我们需要使用该属性,因此我们需要确保它在 -Properties 列表中返回。