Powershell Regex - output error StackTrace as a single line

Viewed 35
$error[0].StackTrace

Produces:

at System.Management.Automation.AutomationEngine.ParseScriptBlock(String script, String fileName, Boolean interactiveCommand)
at System.Management.Automation.Runspaces.Command.CreateCommandProcessor(ExecutionContext executionContext, CommandFactory commandFactory, Boolean addToHistory, CommandOrigin origin)
at System.Management.Automation.Runspaces.LocalPipeline.CreatePipelineProcessor()
at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()
at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc()

I am trying to export this as a single line to an output file using Add-Content or a StreamWriter.

I've achieved this with the following line:

Add-Content -Value $error[0].StackTrace.Replace("`n","").Replace("`r","") -LiteralPath "C:\Temp\delete5.txt"

How can I do this with a single replace function? I've tried various regex strings such as:

/`n|`r/g
/[`n`r]/g

As I understand it I need the / flags and the 'g' flag to ensure it catches all instances, but beyond that I haven't managed to combine the other characters into a single expression successfully. And no other solution to similar problems seems to achieve the desired result.

1 Answers

Use the -replace operator and a regular expression:

Add-Content -Value ($error[0].StackTrace -replace '[\r\n]+') -LiteralPath "C:\Temp\delete5.txt"

You do not need the g flag as the -replace operator matches all non-overlapping occurrences of a pattern in the input string and replaces them with the replacement pattern (here, it removes the matches as the replacement is omitted). In PS, regexps are defined with string literals, not regex literals, so the /.../[flags] notation is not allowed/supported/used, and g flag is not supported even as an inline modifier flag ($s -replace '(?g)[\r\n]+' results in a FullyQualifiedErrorId : InvalidRegularExpression exception).

Related