2016-03-16 63 views
1

我创建了一个基本的脚本为PC添加到域错误。虽然这个工作有错误的余地,我想进行一些错误处理。处理域加入

do { 
    Add-Computer -DomainName $Domain -Credential(get-credential) 
} while (!$?) 

使用!$?在最后一个命令不成功时运行while循环。

不过,也有返回的各种错误。无论PC是否关闭网络,不正确的用户名或密码或域名规范,我希望能够处理这些错误并显示有意义的内容。

一个错误的返回

Add-Computer : This command cannot be executed on target computer('PCName') due to 
following error: Logon failure: unknown user name or bad password. 
At line:1 char:13 
+ Add-Computer <<<< -DomainName $Domain -Credential(get-credential); 
    + CategoryInfo   : InvalidOperation: (PCNAME:String) [Add-Computer], InvalidOperationException 
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.AddComputerCommand

与错误处理工作中可以说VBA,一个错误ID,并给出使用if语句,你可以用它做什么。

以上FullyQualifiedErrorID错误是跨越不同的原因收到的所有错误一样的,所以我不相信我可以使用。

我怎样才能捕捉到特定的错误“登录失败:未知的用户名或密码错误”或其他错误并显示有意义的消息,以便管理员可以采取适当的措施?

回答

2

如果您应该能够使用错误信息的错误区别闲来无事:

do { 
    $joined = $true 
    $cred = Get-Credential 
    try { 
    Add-Computer -DomainName $Domain -Credential $cred -ErrorAction Stop 
    } catch { 
    $joined = $false 
    switch -regex ($_.Exception.Message) { 
     '.*unknown user name.*'  { ... } 
     '.*domain does not exist.*' { ... } 
     ... 
     default      { 'Unexpected error' } 
    } 
    } 
} until ($joined) 

请注意,您需要设置错误动作Stop-ErrorAction Stop),否则错误会无法终止,因此无法捕捉。

+0

谢谢你的回复。我的错误被捕获,但我的while while循环完全被忽略。在这种情况下最好使用真/假标志吗?设置一个变量为“False”,如果发现错误将该变量设置为“True”并将其用作循环的断路器? – user3364233

+0

与语句在'catch'阻止'$?'在循环条件的值可能不是你所期望的。尝试使用状态变量(请参阅更新后的答案)。 –

+0

你好!道歉,终于有一些时间来回到这一点。您的更正已经奏效,并且对此循环使用真/假标志已经奏效。谢谢您的帮助 – user3364233

0

与-ErrorAction参数使用它:

Add-Computer ... -ErrorAction SilentlyContinue -ErrorVariable computerError 

的ErrorVariable是一个数组,所以所产生的误差将被存储在:

$computerError[0] 

要再次反复使用相同的变量,在var名称前使用+:

Add-Computer -ErrorVariable +manyErrors 

而最后一个错误将始终为:

$manyErrors[$manyerrors.count - 1] 

要获得最后一个错误代码,如果它有一个相应的Win32错误代码,然后运行以下

$manyErrors[$manyerrors.count - 1].Exception.InnerException.NativeErrorCode 

,然后如果你收集潜在的错误代码,你可以做以下

if ($manyErrors[$manyerrors.count - 1].Exception.InnerException.NativeErrorCode -eq 1) 
{ 
Write-Host error happened 
} 
elseif ($manyErrors[$manyerrors.count - 1].Exception.InnerException.NativeErrorCode -eq 2) 
Write-Host other error happened 
}