PowerShell脚本优化:生成带时间戳的AD禁用账户日志文件
修复PowerShell AD用户禁用脚本的日志覆盖问题
修复后的完整脚本
Import-Module ActiveDirectory # 配置参数 $inactiveDays = 90 $disableDaysInactive = (Get-Date).AddDays(-$inactiveDays) $DisabledOU = 'OU=Disabled Accounts,OU=Car,DC=car,DC=com' $Path = "OU=Test,OU=User Accounts,OU=Car,DC=car,DC=com" # 生成带时间戳的日志文件名,避免覆盖 $timestamp = Get-Date -Format "yyyyMMdd_HHmmss" $LogDir = "C:\Temp\ADAM" $LogFile = Join-Path -Path $LogDir -ChildPath "Disable_and_Move_User_Accounts_$timestamp.log" # 确保日志目录存在,避免报错 if (-not (Test-Path -Path $LogDir)) { New-Item -ItemType Directory -Path $LogDir -Force | Out-Null } # 优化AD用户查询,仅获取需要的属性,提升效率 $userlist = Get-ADUser -SearchBase $Path -Filter {Enabled -eq $True} -Properties lastLogonDate, Description | Where-Object { $_.Description -notlike "*Service Account*" -and $_.lastLogonDate -lt $disableDaysInactive -and $_.lastLogonDate -ne $null } Start-Transcript -Path $LogFile -Append:$false try { if ($userlist) { Write-Host "`n[INFO] 找到符合条件的用户,开始处理:" foreach ($user in $userlist) { $newDesc = "Disabled on $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') for being inactive - $($user.Description)" try { Set-ADUser -Identity $user -Description $newDesc -Enabled $false -ErrorAction Stop Move-ADObject -Identity $user -TargetPath $DisabledOU -ErrorAction Stop Write-Host "[SUCCESS] 已禁用并移动账户:$($user.SamAccountName) (姓名:$($user.Name))" } catch { Write-Host "[ERROR] 处理账户 $($user.SamAccountName) 失败:$_" } } Write-Host "`n[INFO] 处理完成,共操作 $($userlist.Count) 个账户" } else { Write-Host "[INFO] 未找到符合条件的用户" } } finally { Stop-Transcript }
关键修改说明
- 生成带时间戳的日志文件:通过
Get-Date -Format "yyyyMMdd_HHmmss"生成唯一的日期时间戳,确保每次运行生成独立的日志文件,彻底解决覆盖问题 - 确保日志目录存在:添加目录检查与创建逻辑,避免因目录不存在导致脚本报错
- 优化AD查询性能:将
Properties *改为仅获取lastLogonDate和Description两个必要属性,减少AD服务器负载,提升脚本运行速度 - 增强日志可读性:添加明确的操作状态提示(成功/失败),记录账户的SamAccountName和姓名,方便后续追溯
- 完善错误处理:在AD操作中添加
-ErrorAction Stop确保异常能被catch捕获,同时使用finally块保证Stop-Transcript始终执行,避免转录异常
内容的提问来源于stack exchange,提问作者Dark Night
相关产品推荐
相关产品推荐

