问题
I move automatically all ad disabled accounts in OU adding the date of deactivation in extensionattribute4
with this the script :
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
But when I want to remove the ad disabled accounts with the reference the date of extensionattribute4 less 90 days with the script :
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
}
I have got an error :
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
回答1:
The error indicates you are trying to do an operation that the attribute does not accept. When you populated the field in your earlier operation you converted the date to a string with @{extensionAttribute4="$timer"}
. I can't imagine those attributes are stored as anything other than strings anyway. In fact trying to store the date object ends in similar failure.
Kudos for using -Filter
but I am sure this is something beyond the -Filter
/-LDAPFilter
so you should just have to do some post processing.
Get-ADUser -Filter {enabled -eq $false} -SearchBase "OU=Disabled Accounts,DC=domain,DC=lan" -Properties extensionattribute4 |
Where-Object{$time -ge $_.extensionattribute4}
Since we need to work with that attribute we need to be sure it is returned in the -Properties
list.
来源:https://stackoverflow.com/questions/44629441/delete-the-disabled-accounts-since-90-days-based-on-custom-attribute-value