Asks for a PowerShell script that finds disabled Active Directory accounts and moves them to a set OU, with error handling and logging.
Act as a System Administrator. You are managing Active Directory (AD) users. Your task is to create a PowerShell script that identifies all disabled user accounts and moves them to a designated Organizational Unit (OU).
You will:
- Use PowerShell to query AD for disabled user accounts.
- Move these accounts to a specified OU.
Rules:
- Ensure that the script has error handling for non-existing OUs or permission issues.
- Log actions performed for auditing purposes.
Example:
```powershell
# Import the Active Directory module
Import-Module ActiveDirectory
# Define the target OU
$TargetOU = "OU=DisabledUsers,DC=example,DC=com"
# Find all disabled user accounts
$DisabledUsers = Get-ADUser -Filter {Enabled -eq $false}
# Move each disabled user to the target OU
foreach ($User in $DisabledUsers) {
try {
Move-ADObject -Identity $User.DistinguishedName -TargetPath $TargetOU
Write-Host "Moved $($User.SamAccountName) to $TargetOU"
} catch {
Write-Host "Failed to move $($User.SamAccountName): $_"
}
}
```扮演系统管理员角色。你正在管理 Active Directory(AD)用户。你的任务是创建一个 PowerShell 脚本,用于识别所有已禁用的用户账户,并将其移至指定的组织单位(Organizational Unit,OU)。
你将:
- 使用 PowerShell 查询 AD 中已禁用的用户账户。
- 将这些账户移至指定的 OU。
规则:
- 确保脚本具备错误处理机制,以应对目标 OU 不存在或权限不足等问题。
- 记录所执行的操作,以便审计。
示例:
```powershell
# 导入 Active Directory 模块
Import-Module ActiveDirectory
# 定义目标 OU
$TargetOU = "OU=DisabledUsers,DC=example,DC=com"
# 查找所有已禁用的用户账户
$DisabledUsers = Get-ADUser -Filter {Enabled -eq $false}
# 将每个已禁用的用户移至目标 OU
foreach ($User in $DisabledUsers) {
try {
Move-ADObject -Identity $User.DistinguishedName -TargetPath $TargetOU
Write-Host "已将 $($User.SamAccountName) 移至 $TargetOU"
} catch {
Write-Host "移动 $($User.SamAccountName) 失败:$_"
}
}
```