PowerShell脚本禁用AD非活跃用户报错求助
问题分析与脚本修复
错误原因
出现The requested operation did not satisfy one or more constraints associated with the class of the object错误,核心原因是AD用户的Description属性存在1024字符的长度限制。你的脚本将原用户描述追加到新的禁用说明后,总长度超过了这个限制,触发了AD的属性约束校验。
修复后的脚本
Import-Module ActiveDirectory # 配置参数 $inactiveDays = 40 $disableDaysInactive = (Get-Date).AddDays(-$inactiveDays) $todaysDate = Get-Date -Format "yyyyMMdd_HH-mm-ss" $LogFile = "C:\temp\Test\Disable_and_Move_User_Accounts_$todaysDate.log" $DisabledOU = 'OU=Test Disable,OU=User Accounts,OU=Car,DC=car,DC=com' $searchPath = "OU=Test,OU=User Accounts,OU=Car,DC=car,DC=com" # 启动日志记录(移到脚本开头,确保所有操作被记录) Start-Transcript -Path $LogFile -Append # 仅获取需要的AD属性,提升性能 $userList = Get-ADUser -SearchBase $searchPath -Filter {Enabled -eq $True} -Properties Description, lastLogonDate, DisplayName | Where-Object { $_.Description -notlike "*Service Account*" -and $_.lastLogonDate -lt $disableDaysInactive -and $_.lastLogonDate -ne $null } $disabledUsers = @() if ($userList) { foreach ($user in $userList) { # 处理描述长度:保留原描述的前800字符,避免总长度超1024 $truncatedOriginalDesc = if ($user.Description) { $user.Description.Substring(0, [Math]::Min(800, $user.Description.Length)) } else { "" } $newDesc = "Disabled on $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') for being inactive for 40 days | Original Desc: $truncatedOriginalDesc" try { Set-ADUser -Identity $user -Description $newDesc -Enabled $false Move-ADObject -Identity $user -TargetPath $DisabledOU $disabledUsers += $user.DisplayName } catch { Write-Error "Error updating account $($user.SamAccountName): $_" } } # 按要求格式输出被禁用用户的DisplayName Write-Output "Disabled users:" $disabledUsers | ForEach-Object { Write-Output $_ } } else { Write-Output "No users met the search criteria." } Stop-Transcript
关键修改说明
- 属性优化:将
-Properties *改为仅获取Description, lastLogonDate, DisplayName,减少AD查询的数据量,提升脚本效率。 - 描述长度处理:对原描述进行截断(保留前800字符),确保新生成的描述总长度不超过AD的1024字符限制,避免约束错误。
- 日志位置调整:将
Start-Transcript移到脚本开头,确保脚本所有操作都被记录到日志文件中。 - 用户列表收集:用数组
$disabledUsers统一收集被成功禁用的用户DisplayName,最后按示例格式输出,便于查看。 - 错误输出规范:使用
Write-Error输出错误信息,日志中会更清晰区分正常输出与错误内容。
内容的提问来源于stack exchange,提问作者Dark Night
相关产品推荐
相关产品推荐

