Reputation: 3285
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!
Upvotes: 15
Views: 22358
Reputation:
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 '';
Upvotes: 10
Reputation: 200573
Pipe the command output into the Out-String
cmdlet:
$output = svnlook cat -t $transId -r $repos $filename | Out-String
Upvotes: 19
Reputation: 68341
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
Upvotes: 5