如何动态创建PSCustomObject处理LDAP用户缺失属性?
LDAP搜索结果动态创建PSCustomObject解决方案
在从LDAP服务器获取搜索结果后,需要动态生成PSCustomObject,但部分用户属性(如givenname)并非所有用户都具备,直接按固定属性赋值会报错,例如:
Name = $($item.Attributes['givenname'].GetValues('string')) Surname = $($item.Attributes['sn'].GetValues('string'))
你的尝试代码存在问题:循环为每个属性单独创建PSCustomObject,导致最终结果是多个单属性对象,而非每个用户对应一个包含所有存在属性的对象。同时你提到需要支持重复属性值(LDAP多值属性),以下是可行的实现方式:
正确代码示例
$targetAttrs = "cn","tel","email","sn","givenname","ou" $c.Bind() $searchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $baseDN, $Filter, $scope, $attrlist $searchResponse = $c.SendRequest($searchRequest) $data = @() foreach ($entry in $searchResponse.Entries) { # 用有序哈希表收集当前条目存在的属性,保留目标属性顺序 $entryProperties = [ordered]@{} foreach ($attr in $targetAttrs) { if ($entry.Attributes.Keys -contains $attr) { # 获取属性的所有字符串值(支持多值,满足重复属性值需求) $entryProperties[$attr] = $entry.Attributes[$attr].GetValues([string]) } } # 将哈希表转换为PSCustomObject并加入结果数组 $data += [pscustomobject]$entryProperties }
代码说明
- 使用
[ordered]@{}有序哈希表,确保生成的PSCustomObject属性顺序和你定义的targetAttrs一致 - 遍历目标属性列表,仅保留当前LDAP条目中存在的属性,避免缺失属性导致的报错
- 通过
GetValues([string])获取属性的所有值(返回数组),完美支持LDAP的多值属性(即重复属性值) - 每个LDAP条目对应一个完整的
PSCustomObject,而非拆分多个单属性对象
内容的提问来源于stack exchange,提问作者Zombievirus
相关产品推荐
相关产品推荐

