PowerShell 中的错误和异常是结构化对象。您在控制台上看到的错误消息实际上是一条格式化消息,其中包含来自错误/异常对象的多个元素的信息。您可以像这样(重新)自己构建它:
$formatstring = "{0} : {1}`n{2}`n" +
" + CategoryInfo : {3}`n" +
" + FullyQualifiedErrorId : {4}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
$_.ErrorDetails.Message,
$_.InvocationInfo.PositionMessage,
$_.CategoryInfo.ToString(),
$_.FullyQualifiedErrorId
$formatstring -f $fields
如果您只想将错误消息显示在您的catch
块你可以简单地回显当前对象变量(它保存当时的错误):
try {
...
} catch {
$_
}
如果您需要彩色输出,请使用Write-Host
使用如上所述的格式化字符串:
try {
...
} catch {
...
Write-Host -Foreground Red -Background Black ($formatstring -f $fields)
}
话虽如此,通常您不想只在异常处理程序中按原样显示错误消息(否则-ErrorAction Stop
将毫无意义)。结构化错误/异常对象为您提供了可用于更好的错误控制的附加信息。例如你有$_.Exception.HResult
与实际的错误号。$_.ScriptStackTrace
and $_.Exception.StackTrace
,这样您就可以在调试时显示堆栈跟踪。$_.Exception.InnerException
使您可以访问通常包含有关错误的附加信息的嵌套异常(顶级 PowerShell 错误可能有些通用)。您可以使用如下方式展开这些嵌套异常:
$e = $_.Exception
$msg = $e.Message
while ($e.InnerException) {
$e = $e.InnerException
$msg += "`n" + $e.Message
}
$msg
在你的情况下,你想要提取的信息似乎在$_.ErrorDetails.Message
。我不太清楚你是否有一个对象或一个 JSON 字符串,但你应该能够获取有关成员的类型和值的信息$_.ErrorDetails
通过跑步
$_.ErrorDetails | Get-Member
$_.ErrorDetails | Format-List *
If $_.ErrorDetails.Message
是一个对象,您应该能够像这样获取消息字符串:
$_.ErrorDetails.Message.message
否则你需要先将 JSON 字符串转换为对象:
$_.ErrorDetails.Message | ConvertFrom-Json | Select-Object -Expand message
根据您正在处理的错误类型,特定类型的异常还可能包含有关当前问题的更具体信息。例如,在你的情况下,你有一个WebException
除了错误消息($_.Exception.Message
) 包含来自服务器的实际响应:
PS C:\> $e.Exception | Get-Member
TypeName: System.Net.WebException
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj), bool _Exception.E...
GetBaseException Method System.Exception GetBaseException(), System.Excep...
GetHashCode Method int GetHashCode(), int _Exception.GetHashCode()
GetObjectData Method void GetObjectData(System.Runtime.Serialization.S...
GetType Method type GetType(), type _Exception.GetType()
ToString Method string ToString(), string _Exception.ToString()
Data Property System.Collections.IDictionary Data {get;}
HelpLink Property string HelpLink {get;set;}
HResult Property int HResult {get;}
InnerException Property System.Exception InnerException {get;}
Message Property string Message {get;}
Response Property System.Net.WebResponse Response {get;}
Source Property string Source {get;set;}
StackTrace Property string StackTrace {get;}
Status Property System.Net.WebExceptionStatus Status {get;}
TargetSite Property System.Reflection.MethodBase TargetSite {get;}
它为您提供如下信息:
PS C:\> $e.Exception.Response
IsMutuallyAuthenticated : False
Cookies : {}
Headers : {Keep-Alive, Connection, Content-Length, Content-T...}
SupportsHeaders : True
ContentLength : 198
ContentEncoding :
ContentType : text/html; charset=iso-8859-1
CharacterSet : iso-8859-1
Server : Apache/2.4.10
LastModified : 17.07.2016 14:39:29
StatusCode : NotFound
StatusDescription : Not Found
ProtocolVersion : 1.1
ResponseUri : http://www.example.com/
Method : POST
IsFromCache : False
由于并非所有异常都具有完全相同的属性集,因此您可能需要对特定异常使用特定的处理程序:
try {
...
} catch [System.ArgumentException] {
# handle argument exceptions
} catch [System.Net.WebException] {
# handle web exceptions
} catch {
# handle all other exceptions
}
如果您有无论是否发生错误都需要完成的操作(清理任务,例如关闭套接字或数据库连接),您可以将它们放在finally
异常处理后阻塞:
try {
...
} catch {
...
} finally {
# cleanup operations go here
}