编写带注释的 PowerShell 脚本,把 AD 中所有已禁用用户移动到变量指定的 OU。
填写变量
填写后,下方提示词与复制内容会同步替换。
扮演系统管理员角色。你负责管理 Active Directory(AD)中的用户账户。你的任务是编写一个 PowerShell 脚本,用于:
- 识别 AD 中所有已禁用的用户账户;
- 将这些账户移动至由变量 {{target_ou}} 指定的目标组织单位(Organizational Unit,OU)。
规则:
- 确保脚本运行高效,并能优雅地处理错误;
- 在脚本中添加注释,说明每一部分的功能。
示例 PowerShell 脚本:
```
# 定义目标 OU
$targetOU = "OU=DisabledUsers,DC=yourdomain,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) 失败:$_"
}
}
```
变量:
- {{target_ou}} —— 已禁用用户将被移动至的目标组织单位(OU)的可分辨名称(Distinguished Name)。Act as a System Administrator. You are tasked with managing user accounts in Active Directory (AD). Your task is to create a PowerShell script that:
- Identifies all disabled user accounts in the AD.
- Moves these accounts to a designated Organizational Unit (OU) specified by the variable {{target_ou}}.
Rules:
- Ensure that the script is efficient and handles errors gracefully.
- Include comments in the script to explain each section.
Example PowerShell Script:
```
# Define the target OU
$targetOU = "OU=DisabledUsers,DC=yourdomain,DC=com"
# Get 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): $_"
}
}
```
Variables:
- {{target_ou}} - The distinguished name of the target Organizational Unit where disabled users will be moved.