You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本中如何添加SearchBase筛选指定OU并移动AD用户?

解决AD用户移动脚本的OU过滤问题

你需要在脚本中添加逻辑,只处理位于指定「Users OU」内的用户,以下是两种可行的实现方式:

方式一:先获取用户再验证所在OU

这种方式先获取域内的用户对象,再检查其是否属于目标OU,适合需要额外处理非目标OU用户的场景:

$inactiveAzure = Import-CSV -Path "C:\temp\InactiveAzure.csv"

# 替换为实际的Users OU完整LDAP路径,例如 "OU=Users,DC=contoso,DC=com"
$OUpath = "OU=Users,DC=yourdomain,DC=com" 

# 替换为实际的Inactive OU完整LDAP路径
$OUTarget = "OU=Inactive Users,DC=yourdomain,DC=com"

ForEach($user in $inactiveAzure) {
    # 获取AD用户对象,忽略不存在的用户避免报错
    $adUser = Get-ADUser -Identity $user.onPremisesSamAccountName -ErrorAction SilentlyContinue
    
    if ($adUser) {
        # 验证用户是否在指定的Users OU中(通过DistinguishedName匹配)
        if ($adUser.DistinguishedName -like "*$OUpath") {
            # 移动用户到目标OU
            Move-ADObject -Identity $adUser -TargetPath $OUTarget
            Write-Host "成功移动用户: $($adUser.SamAccountName)"
        } else {
            Write-Host "用户 $($adUser.SamAccountName) 不在指定OU内,跳过"
        }
    } else {
        Write-Host "未找到用户: $($user.onPremisesSamAccountName),跳过"
    }
}

方式二:直接在搜索时限制OU范围

这种方式通过-Filter和-SearchBase参数,仅在指定OU内查找用户,避免后续验证步骤:

$inactiveAzure = Import-CSV -Path "C:\temp\InactiveAzure.csv"

$OUpath = "OU=Users,DC=yourdomain,DC=com" 
$OUTarget = "OU=Inactive Users,DC=yourdomain,DC=com"

ForEach($user in $inactiveAzure) {
    # 仅在指定OU内搜索匹配SamAccountName的用户
    $adUser = Get-ADUser -Filter "SamAccountName -eq '$($user.onPremisesSamAccountName)'" `
                         -SearchBase $OUpath `
                         -ErrorAction SilentlyContinue
    
    if ($adUser) {
        Move-ADObject -Identity $adUser -TargetPath $OUTarget
        Write-Host "成功移动用户: $($adUser.SamAccountName)"
    } else {
        Write-Host "用户 $($user.onPremisesSamAccountName) 不存在或不在指定OU内,跳过"
    }
}

关键说明:

  • 必须将$OUpath和$OUTarget替换为完整的LDAP格式路径,可通过AD用户和计算机工具查看OU的「distinguishedName」属性获取。
  • 使用-ErrorAction SilentlyContinue避免因用户不存在导致脚本中断。
  • 方式二更高效,因为它直接限定了搜索范围,减少了不必要的AD查询。

内容的提问来源于stack exchange,提问作者Ackerman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 07:43:26