PowerShell导入模块时DirectorySearcher调用FindAll报错问题
故障现象
通过Import-Module导入封装好的LDAP查询函数并调用时,抛出如下异常:
Exception calling "FindAll" with "0" argument(s): "Det finns inte något sådant objekt på servern.
排查过程中已确认以下信息:
- 尝试调整逻辑,直接返回
$Searcher对象后在外部手动执行findAll()方法,仍然触发完全相同的报错 - 直接运行脚本本体、或是把函数代码直接嵌入其他脚本中执行时,逻辑完全正常,仅通过
Import-Module导入模块的方式调用会出现异常(代码中服务器地址、端口、密码等敏感信息已做匿名替换) - 尝试改用dot-sourcing(点源)方式加载脚本,报错完全一致;其余脚本使用这两种加载方式均能正常运行
- 可以确认函数已被成功加载(报错触发位置就在函数内部),所有入参传递均正确,但
DirectorySearcher组件始终无法正常工作
关联函数代码
Function Search-HSA { Param ( [parameter(Mandatory = $false)] $LDAPServer = "LDAP://[Server]:[port]/", [parameter(Mandatory = $false)] $LDAPSearchBase = "[Searchbase]", [parameter(Mandatory = $true)] $LDAPFilter, [parameter(Mandatory = $false)] $LDAPSearchScope = "Subtree" ) $Path = $LDAPServer + $LDAPSearchBase $LDAPAuth = [System.DirectoryServices.AuthenticationTypes]::Anonymous $LDAPUser = "cn=user,ou=accounts,ou=admin,o=org,c=de" $LDAPPassword = "[password]" $LDAPObj = New-Object System.DirectoryServices.DirectoryEntry($Path, $LDAPUser, $LDAPPassword, $LDAPAuth) $Properties = "*" $Searcher = New-Object DirectoryServices.DirectorySearcher($LDAPObj, $LDAPFilter) $Searcher.PageSize = 1000 $Searcher.SearchScope = $LDAPSearchScope $Properties | ForEach-Object { [void]$Searcher.PropertiesToLoad.Add($_) } $Result = $Searcher.findAll() Return $Result } #End function
根因定位
编辑补充:已定位到问题根因,是脚本文件使用了UTF-8编码,而非要求的UTF-16LE编码。
内容的提问来源于stack exchange,提问作者Jonathan Svahn
相关产品推荐
相关产品推荐

