Powershell 处理域加入错误
我已经创建了一个基本脚本来添加一台PC到域中。虽然这是可行的,但还是有出错的空间,我想加入一些错误处理Powershell 处理域加入错误,powershell,Powershell,我已经创建了一个基本脚本来添加一台PC到域中。虽然这是可行的,但还是有出错的空间,我想加入一些错误处理 do { Add-Computer -DomainName $Domain -Credential(get-credential) } while (!$?) 使用!$?在最后一个命令未成功时运行while循环 但是,会返回各种错误。无论电脑是否已脱离网络、用户ID或密码不正确或域规范不正确,我都希望能够处理这些错误并显示有意义的内容 返回了一个错误 Add-Computer : Thi
do {
Add-Computer -DomainName $Domain -Credential(get-credential)
} while (!$?)
使用!$?在最后一个命令未成功时运行while循环
但是,会返回各种错误。无论电脑是否已脱离网络、用户ID或密码不正确或域规范不正确,我都希望能够处理这些错误并显示有意义的内容
返回了一个错误
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
添加计算机:由于以下原因,无法在目标计算机(“PCName”)上执行此命令:
以下错误:登录失败:未知用户名或错误密码。
第1行字符:13
+添加计算机如果没有其他错误,您应该能够使用错误消息来区分错误:
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
),否则错误将不会终止,因此无法捕获。将其与-ErrorAction参数一起使用:
Add-Computer ... -ErrorAction SilentlyContinue -ErrorVariable computerError
ErrorVariable是一个数组,因此产生的错误将存储在:
$computerError[0]
要反复使用同一变量,请在变量名称前使用+号:
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
}
然后,如果您收集了潜在的错误代码,您可以执行以下操作
$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
}
谢谢你的回复。我的错误被捕获,但我的do while循环被完全忽略。在这种情况下,是否最好使用真/假标志?将变量设置为“False”,如果发现错误,则将变量设置为“True”,并将其用作循环的“我的断路器”?在
catch
块中使用语句循环条件中$?
的值可能不是您所期望的。尝试使用状态变量(请参阅更新的答案)。您好!抱歉,终于有时间回到这件事上了。您的更正已生效,为此循环使用真/假标志已生效。谢谢你的帮助