Powershell:使用try-and-catch处理错误
我正在写一个脚本,希望控制错误。但是,我在使用try,catch查找错误处理信息时遇到困难。我希望捕获特定错误(如下所示),然后执行一些操作并恢复代码。这需要什么代码 这是我正在运行的代码,当出现提示时,我输入的用户名无效Powershell:使用try-and-catch处理错误,powershell,error-handling,try-catch,Powershell,Error Handling,Try Catch,我正在写一个脚本,希望控制错误。但是,我在使用try,catch查找错误处理信息时遇到困难。我希望捕获特定错误(如下所示),然后执行一些操作并恢复代码。这需要什么代码 这是我正在运行的代码,当出现提示时,我输入的用户名无效 Get-WMIObject Win32_Service -ComputerName localhost -Credential (Get-Credential) Get-WmiObject : User credentials cannot be used for lo
Get-WMIObject Win32_Service -ComputerName localhost -Credential (Get-Credential)
Get-WmiObject : User credentials cannot be used for local connections
At C:\Users\alex.kelly\AppData\Local\Temp\a3f819b4-4321-4743-acb5-0183dff88462.ps1:2 char:16
+ Get-WMIObject <<<< Win32_Service -ComputerName localhost -Credential (Get-Credential)
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
获取WMIObject Win32_服务-计算机名本地主机-凭据(获取凭据)
Get-WMIOObject:用户凭据不能用于本地连接
在C:\Users\alex.kelly\AppData\Local\Temp\a3f819b4-4321-4743-acb5-0183dff88462.ps1:2字符:16
+获取WMIObject您必须使用-erroraction stop
进入try/catch
或trap
脚本块。您可以测试以下内容:
Clear-Host
$blGoOn = $true
while ($blGoOn)
{
trap
{
Write-Host $_.exception.message
continue
}
Get-WMIObject Win32_Service -ComputerName $computer -Credential (Get-Credential) -ErrorAction Stop
if ($?)
{
$blGoOn=$false
}
}
在尝试捕获[System.Management.ManagementException]类型的异常时,有人能理解为什么我不能捕获此异常吗
PowerShell应该能够捕获与某些异常类匹配的异常,但即使下面的异常类是[System.Management.ManagementException],它也不会在该捕获块中捕获它
i、 e:
工作原理与:
Try
{
Get-WMIObject Win32_Service -ComputerName localhost -Credential (Get-Credential) -ErrorAction "Stop"
}
Catch [Exception]
{
Write-Host "Generic Exception"
Write-Host $_
$_ | Select *
}
对我来说没有意义
您也可以在通用异常捕获块中捕获错误,然后检查文本是否与您要查找的单词匹配,但它有点脏。感谢您的快速回复。特别是,如何捕获错误消息“用户凭据不能用于本地连接”?其他错误需要用不同的代码处理。谢谢你说得对:“用户凭据不能用于本地连接”
Try
{
Get-WMIObject Win32_Service -ComputerName localhost -Credential (Get-Credential) -ErrorAction "Stop"
}
Catch [Exception]
{
Write-Host "Generic Exception"
Write-Host $_
$_ | Select *
}