try { // Some code that may throw an error } catch (Exception ex) { ErrorRecord error = new ErrorRecord(ex, "ErrorId", ErrorCategory.InvalidOperation, null); Console.WriteLine(error.ToString()); }
private static void DisplayErrors(ErrorRecord error) { Console.WriteLine("Error message: " + error.Exception.Message); Console.WriteLine("Error source: " + error.Exception.Source); Console.WriteLine("Error target site: " + error.Exception.TargetSite); }In this example, we define a method called DisplayErrors that takes an ErrorRecord object as a parameter. We then extract the error message, error source, and error target site from the exception object and display them using Console.WriteLine. The System.Management.Automation namespace is part of the Microsoft.PowerShell.5.1.ReferenceAssemblies package.