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

向Get-ADUser cmdlet传递变量失败的问题求助

解决PowerShell遍历OU获取AD用户的问题

嘿,这个问题我之前也碰到过!核心问题出在你传递给Get-ADUser的$ou变量上——它不是一个纯字符串的可分辨名称(DN),而是一个PowerShell自定义对象,这就导致AD cmdlet无法识别它作为有效的搜索路径。

让我给你拆解一下:当你用select-object -Property distinguishedName的时候,返回的是包含distinguishedName属性的对象集合,而不是直接的DN字符串。所以在循环里$ou其实是类似@{distinguishedName="OU=xxx,DC=company,DC=local"}的对象,不是AD cmdlet需要的纯文本DN。

两种快速修复方法:

方法1:直接提取DN字符串(推荐)

修改get-adorganizationalunit的输出,用-ExpandProperty直接获取字符串数组:

Import-Module ActiveDirectory
# 用-ExpandProperty直接得到纯DN字符串的数组
$SearchBase = Get-ADOrganizationalUnit -Filter * -SearchBase "ou=users,ou=myUsers,dc=company,dc=local" -Properties CanonicalName | Select-Object -ExpandProperty distinguishedName

foreach ($ou in $SearchBase) {
    # 这里$ou就是纯DN字符串,直接传给-SearchBase
    Get-ADUser -Filter * -SearchBase $ou -Properties givenName,sn,mail
}

方法2:在循环中访问对象属性

如果需要保留原对象的其他属性,也可以在循环里明确指定$ou.distinguishedName:

Import-Module ActiveDirectory
$SearchBase = Get-ADOrganizationalUnit -Filter * -SearchBase "ou=users,ou=myUsers,dc=company,dc=local" -Properties CanonicalName | Select-Object -Property distinguishedName

foreach ($ou in $SearchBase) {
    # 访问对象的distinguishedName属性,传递纯字符串
    Get-ADUser -Filter * -SearchBase $ou.distinguishedName -Properties givenName,sn,mail
}

为什么之前会报错?

你看到的"The supplied distinguishedName must belong to one of the following partitions..."错误,本质是因为AD cmdlet接收到的不是有效的DN字符串,而是一个对象,它无法解析这个对象对应的AD分区,所以抛出了这个提示。

这样修改后,Get-ADUser就能正确识别每个OU的DN作为搜索路径,顺利获取每个OU下的用户信息啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:41:56