Skip to content

Commit f29c9cf

Browse files
authored
Improve error logging for exec of pscommands (#598)
* Improve error logging for exec of pscommands * Handle null ScriptStackTrace - not sure it's possible but just in case * Tweak log output format and kick new build
1 parent 0f63e5c commit f29c9cf

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

src/PowerShellEditorServices/Session/PowerShellContext.cs

+32-2
Original file line numberDiff line numberDiff line change
@@ -534,13 +534,43 @@ await Task.Factory.StartNew<IEnumerable<TResult>>(
534534

535535
if (this.powerShell.HadErrors)
536536
{
537-
string errorMessage = "Execution completed with errors:\r\n\r\n";
537+
// Get the command/params that we were trying execute as a string in order to log it
538+
string commandText = "";
539+
foreach (var cmd in psCommand.Commands)
540+
{
541+
commandText += cmd.CommandText;
542+
foreach (var param in cmd.Parameters)
543+
{
544+
commandText += $" -{param.Name} {param.Value}";
545+
}
546+
commandText += ";";
547+
}
548+
549+
var strBld = new StringBuilder(1024);
550+
strBld.Append($"Execution of command '{commandText}' completed with errors:\r\n\r\n");
538551

552+
int i = 1;
539553
foreach (var error in this.powerShell.Streams.Error)
540554
{
541-
errorMessage += error.ToString() + "\r\n";
555+
if (i > 1) strBld.Append("\r\n\r\n");
556+
strBld.Append($"Error #{i++}:\r\n");
557+
strBld.Append(error.ToString() + "\r\n");
558+
strBld.Append("ScriptStackTrace:\r\n");
559+
strBld.Append((error.ScriptStackTrace ?? "<null>") + "\r\n");
560+
strBld.Append($"Exception:\r\n {error.Exception?.ToString() ?? "<null>"}");
561+
Exception innerEx = error.Exception?.InnerException;
562+
while (innerEx != null)
563+
{
564+
strBld.Append($"InnerException:\r\n {innerEx.ToString()}");
565+
innerEx = innerEx.InnerException;
566+
}
542567
}
543568

569+
// We've reported these errors, clear them so they don't keep showing up.
570+
this.powerShell.Streams.Error.Clear();
571+
572+
var errorMessage = strBld.ToString();
573+
544574
errorMessages?.Append(errorMessage);
545575
this.logger.Write(LogLevel.Error, errorMessage);
546576

0 commit comments

Comments
 (0)