Home > other >  Is there a way to set the default EOL separator for Out-File in PowerShell 5.1?
Is there a way to set the default EOL separator for Out-File in PowerShell 5.1?

Time:01-31

I am looking for a way to set the default EOL marker to 0x0A when writing text with Out-File.

On the internet, I found tons of examples that either replace 0x0D 0x0A after a file is already written, or -join the lines on 0x0A and then write the concatenated text into the file.

I find both approaches a bit clumsy as I'd just like to write the files with the redirection operator >.

So, is there a way to set the EOL style in PowerShell 5.1?

CodePudding user response:

No, unfortunately, as of PowerShell 7.2, there is no way to make PowerShell use a different newline (EOL, line break) format.

It is the platform-native newline character or sequence (as reflected in [Environment]::NewLine) that is invariably used - both for separating multiple input objects and for the trailing newline by default.

To control the newline format, you need to:

  • Join the input objects explicitly with the newline character (sequence) of choice, using the -join operator, followed by another instance if a trailing newline is desired ...

  • ... and use the -NoNewLine switch of Set-Content / Out-File (in lieu of >) so as to prevent appending of a trailing platform-native newline.

As for potential future enhancements:

  • GitHub feature request #2872 suggests adding a parameter to Set-Content, specifically, to allow specifying the newline format; the request has been green-lighted (a long time ago), but has yet to be implemented - however, I think it isn't comprehensive enough, and it wouldn't help with Out-File / >; see next point.

  • GitHub feature request #3855 more generally asked for a -Delimiter parameter (to mirror Get-Content's existing parameter by that name) to be added to Set-Content / Add-Content, Out-File and Out-String

    • Unfortunately, the proposal was rejected; if it hadn't, you would have been able to configure > - a virtual alias of Out-File - to use LF-only newlines, for instance, as follows:

      # WISHFUL THINKING 
      $PSDefaultParameterValues['Out-File:Delimiter'] = "`n"
      
  •  Tags:  
  • Related