Handling errors with ADSI

假装没事ソ 提交于 2019-12-11 17:58:19

问题


I'm working on a PowerShell script to change a local account name. Of course, the first step is to check that the account exists:

$user=[ADSI]"WinNT://$server/$oldName,user"

If the account exists, then no problem. But if it doesn't, then I get this error:

format-default : The following exception occurred while retrieving member >"distinguishedName": "The user name could not be found." + CategoryInfo : NotSpecified: (:) [format-default], ExtendedTypeSystemException + FullyQualifiedErrorId : CatchFromBaseGetMember,Microsoft.PowerShell.Commands.FormatDefaultCommand

I can't figure out how to look for that error, report something like "$oldName not found" and continue on. From what I can tell, it isn't being thrown into an error variable, so I can't search for a "user name could not be found" string. Try-Catch-Finally seems to ignore the error.

I admit I'm weak on error-handling. It seems there's countless ways for something to fail, and my users always find new ones when using my scripts.


回答1:


It seems like the command is actually throwing a terminating error. From about_preference_variables

"Neither $ErrorActionPreference nor the ErrorAction common parameter affect how Windows PowerShell responds to terminating errors (those that stop cmdlet processing)."

So when the command runs it is terminating the script even before it can move on to try and process a catch block.

Interestingly if you put it into a variable this behavior stops happening. I'd be curious to see if anyone has a better answer, but it looks like the solution from what I can see, would be an if statement based on the results of the variable.

$User = [ADSI]"WinNT://badserver/Name,user" 
If (! $User.Name)
{
    Throw "Issue retrieving user"
}

#Rest of script can continue here



回答2:


You can check whether a username exists in this way

[ADSI]::Exists("WinNT://$Server/$UserName")

It returns a Boolean value. If user exists, you get true, otherwise false.




回答3:


I solved a similar issue by wrapping the command in a script block and using Invoke-Command.

$ChangePassword = {([adsi]"WinNT://domain/$Username,user").ChangePassword($CurrentPassword, $NewPassword)}
try {
    Invoke-Command -ScriptBlock $ChangePassword -ErrorAction Stop
}
catch {
    # Error handling code
}


来源:https://stackoverflow.com/questions/26262384/handling-errors-with-adsi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!