如何通过ADSI LDAP查询extensionAttribute1并输出到Out-GridView
PowerShell查询AD计算机属性并输出到Out-GridView修复方案
问题根因
- 输出结构错误:原有脚本在循环中直接逐个输出4个属性的原始值,没有封装为结构化对象,导致Out-GridView只能识别为零散字符串,无有效列名
- 属性读取错误:
DirectorySearcher返回的属性集合为数组类型,直接输出会显示集合类型标识而非实际值,且属性名匹配规则容易出现大小写/拼写偏差 - 额外输出干扰:
PropertiesToLoad.Add()方法会返回数值类型的索引值,原有脚本未屏蔽该返回值,导致无关数值混入最终输出 - 资源泄漏隐患:原有释放逻辑仅释放最后一个域的搜索器对象,多域查询时会残留未释放资源
修复后完整脚本
$objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() $Domains = $objForest.Domains.Name $FindADComputerName = '*SVR*' foreach ($Domain in $Domains) { $ADsPath = [ADSI]"LDAP://$Domain" $objSearcher = New-Object System.DirectoryServices.DirectorySearcher($ADsPath) $objSearcher.Filter = "(& (objectClass=computer)(!userAccountControl:1.2.840.113556.1.4.803:=2)(operatingSystem=*Server*)(name=$FindADComputerName))" $objSearcher.SearchScope = "Subtree" # 屏蔽Add方法的返回值,避免无关数值混入输出 [void]$objSearcher.PropertiesToLoad.Add("name") [void]$objSearcher.PropertiesToLoad.Add("description") [void]$objSearcher.PropertiesToLoad.Add("operatingsystem") [void]$objSearcher.PropertiesToLoad.Add("extensionattribute1") $colResults = $objSearcher.FindAll() foreach ($objResult in $colResults) { # 封装为自定义对象输出,Out-GridView可直接识别属性为列 [PSCustomObject]@{ 计算机名 = $objResult.Properties['name'][0] 描述 = $objResult.Properties['description'][0] ?? $null 操作系统 = $objResult.Properties['operatingsystem'][0] ExtensionAttribute1 = $objResult.Properties['extensionattribute1'][0] ?? $null } } # 及时释放当前域的搜索器资源 $objSearcher.Dispose() } | Out-GridView -Title "AD服务器账号查询结果"
修改说明
- 结构化输出:将每个计算机的属性封装为
PSCustomObject,明确指定属性名,Out-GridView会自动将属性名作为列名展示 - 修正属性取值:通过
$objResult.Properties['属性名'][0]的方式取值,取出属性集合中的第一个实际值,避免集合类型显示异常,同时用索引取值的方式兼容大小写差异,空值补充?? $null避免取值报错 - 优化过滤逻辑:将sAMAccountName过滤改为name属性过滤,避免计算机账号自带的$后缀导致匹配遗漏,若需保留sAMAccountName过滤可将过滤值改为
$FindADComputerName*$ - 简化冗余逻辑:直接通过
$objForest.Domains.Name获取域名列表,省略冗余的中间变量转换 - 补充空值兼容:对可空属性添加空值判断,避免属性未配置时出现索引取值报错
内容的提问来源于stack exchange,提问作者Senior Systems Engineer
相关产品推荐
相关产品推荐

