我正在尝试捕获远程PoSH脚本中的异常,并且我将获得不同的行为,具体取决于它是本地还是远程PoSH会话。第一个代码按预期工作,无法启用用户,因为它没有密码,因此被ADPasswordComplexityException catch捕获。
import-module activedirectory
try { Set-ADUser user123 -ErrorAction "stop" -Enabled $true }
catch [Microsoft.ActiveDirectory.Management.ADPasswordComplexityException] { write-host "gotya" }
catch { write-host "err" }
..导致gotya被写入。无论我是在本地DC还是其他PC上运行代码,都会发生这种情况。那里一切都很好。
然而,当通过远程会话执行此操作时,不仅初始捕获不起作用,第二次捕获也不起作用。
$ADS = New-PSSession -computername dc.domain -Authentication default -Credential $(get-credential)
Import-Module ActiveDirectory -PSSession $ADS
try { Set-ADUser user123 -ErrorAction "stop" -Enabled $true }
catch [Microsoft.ActiveDirectory.Management.ADPasswordComplexityException] { write-host "gotya" }
catch { write-host "err" }
远程运行时返回(可能会跳过所有捕获):
The password does not meet the length, complexity, or history requirement of the domain.
+ CategoryInfo : InvalidData: (user123:ADUser) [Set-ADUser], ADPasswordComplexityException
+ FullyQualifiedErrorId : The password does not meet the length, complexity, or history requirement of the etc..
此外,当我在DC本地运行远程脚本时,我得到了一个不同的错误:
Unable to find type [Microsoft.ActiveDirectory.Management.ADPasswordComplexityException]: make sure that the assembly
containing this type is loaded.
At line:1 char:7
+ try { Set-ADUser -ErrorAction "stop" user123 -Enabled $true }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Activ...lexityException:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
为什么PoSH讨厌我的想法?提前谢谢。