我正在使用PowerShell脚本来更改本地帐户名称。当然,第一步是检查帐户是否存在:
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:在检索成员> distinguishedName时发生以下异常:找不到用户名。 + CategoryInfo:未指定:(:) [format-default],ExtendedTypeSystemException + FullyQualifiedErrorId: CatchFromBaseGetMember,Microsoft.PowerShell.Commands.FormatDefaultCommand
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
我不知道如何查找该错误,报告类似 $ oldName not found的内容,然后继续。据我所知,它没有被放入错误变量中,因此我无法搜索找不到用户名字符串。最终,Try-Catch-似乎忽略了该错误。
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.
推荐答案该命令实际上引发了终止错误。来自about_preference_variables
It seems like the command is actually throwing a terminating error. From about_preference_variables
$ ErrorActionPreference或ErrorAction公用参数都不会影响Windows PowerShell对终止错误的响应(那些终止cmdlet处理的)。
"Neither $ErrorActionPreference nor the ErrorAction common parameter affect how Windows PowerShell responds to terminating errors (those that stop cmdlet processing)."
因此,当命令运行时,它甚至在脚本继续尝试并处理catch块之前就终止了脚本。
So when the command runs it is terminating the script even before it can move on to try and process a catch block.
放入变量中,则此行为停止发生。我很想知道是否有人有更好的答案,但是从我所看到的解决方案来看,这似乎是一个基于变量结果的if语句。
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更多推荐
使用ADSI处理错误
发布评论