15

I am trying to capture the output of running an external command as a string, but the result returned by Powershell is always an array of strings. It is my understanding that Powershell splits the output on newlines (Windows or Unix line endings) and stores the result in an array, but I would like these newlines to be preserved since this is for an svn pre-commit hook script to detect if a committed file has mixed line endings.

$output = svnlook cat -t $transId -r $repos $filename

At this point line endings have been stripped, and $output is an array of strings, one per line of output.

Redirecting to a file does not seem to work since this normalizes the line endings. How do you tell Powershell to not split a command's output?

Thanks!

3 Answers 3

20

Pipe the command output into the Out-String cmdlet:

$output = svnlook cat -t $transId -r $repos $filename | Out-String
Sign up to request clarification or add additional context in comments.

Comments

10

Just wrap the "inner" command in parentheses, and use the -join operator with "`n" on the right.

# Preserve line breaks
$result = (ipconfig) -join "`n";

# Remove line breaks
$result = (ipconfig) -join '';

Comments

5

If you need it as a single string, you can just cast the result to [string]

[string]$output = svnlook cat -t $transId -r $repos $filename

1 Comment

Note that tis concatenates the lines without putting newlines in, as opposed to the out-string solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.