Объекты ошибок имеют ряд свойств.Вывод $Error[0] | Get-Member | Select Name | Set-Clipboard
:
Имя
Равно
GetHashCode
GetObjectData
GetType
ToString
CategoryInfo
ErrorDetails
Исключение
FullyQualifiedErrorId InvocationInfo
PipelineIterationInfo ScriptStackTrace
TargetObject
PSMessageDetails
Таким образом, вы можете вывести данные на консоль с помощью функции, например:
Function Write-ErrorDetails($ErrorObject)
{
$thisError = [PSCustomObject]@{
Exception = $ErrorObject.Exception
Message = $ErrorObject.Exception.Message
FQID = $ErrorObject.FullyQualifiedErrorId
InovcationInfo = $ErrorObject.InvocationInfo
ScriptStackTrace = $ErrorObject.ScriptStackTrace
TargetObject = $ErrorObject.TargetObject
}
return $thisError
}
В вашемскрипт, если у вас есть блок try / catch, вы можете перехватить исключения и вызвать вашу функцию:
BEGIN
{
Function Write-ErrorDetails($ErrorObject)
{
$thisError = [PSCustomObject]@{
Exception = $ErrorObject.Exception
Message = $ErrorObject.Exception.Message
FQID = $ErrorObject.FullyQualifiedErrorId
InovcationInfo = $ErrorObject.InvocationInfo
ScriptStackTrace = $ErrorObject.ScriptStackTrace
TargetObject = $ErrorObject.TargetObject
}
return $thisError
}
}
PROCESS
{
try
{
Do-SomeNonExistentCommand
}
catch
{
Write-ErrorDetails -ErrorObject $Error[0]
}
}
END{}
Если сохранить внутри файла с именем 123.ps1 и запустить, ваш вывод будет выглядеть так:
Exception : System.Management.Automation.CommandNotFoundException: The term
'Do-SomeNonExistentCommand' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.
at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(
FunctionContext funcContext, Exception exception)
at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(Int
erpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction
.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction
.Run(InterpretedFrame frame)
Message : The term 'Do-SomeNonExistentCommand' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try
again.
FQID : CommandNotFoundException
InovcationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock><Process>, C:\Users\Pythagoras\desktop\123.ps1: line 22
at <ScriptBlock>, <No file>: line 1
TargetObject : Do-SomeNonExistentCommand
Свойство ScriptStackTrace
может быть полезно для устранения неполадок, особенно если вы пишете сценарии / инструменты для аудитории, а не только для собственного использования.Вы можете добавить дополнительные функции для ведения журнала с объектами, которые Write-ErrorDetails
могут предоставить, и т. Д. И т. Д.
Надеюсь, это поможет!