Prevent trailing newline in PowerShell Out-File command

后端 未结 3 662
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 17:20

How do I prevent PowerShell\'s Out-File command from appending a newline after the text it outputs?

For example, running the following command produces a file with c

3条回答
  •  Happy的楠姐
    2020-12-15 17:25

    To complement briantist's helpful answer re -NoNewline:

    The following applies not just to Out-File, but analogously to Set-Content / Add-Content as well; as stated, -NoNewline requires PSv5+.

    Note that -NoNewline means that with multiple objects to output, it is not just a trailing newline (line break) that is suppressed, but any newlines.

    In other words: The string representations of the input objects are directly concatenated, without a separator (terminator).

    Therefore, the following commands result in the same file contents (TestTest without a trailing newline):

    # Single input string
    "TestTest" | Out-File -encoding ascii test.txt -NoNewline
    
    # Equivalent command: 2-element array of strings that are directly concatenated.
    "Test", "Test" | Out-File -encoding ascii test.txt -NoNewline
    

    In order to place newlines only between, but not also after the output objects, you must join the objects with newlines explicitly:

    "Test", "Test" -join [Environment]::NewLine |
      Out-File -encoding ascii test.txt -NoNewline
    

    [Environment]::NewLine is the platform-appropriate newline sequence (CRLF on Windows, LF on Unix-like platforms); you can also produce either sequence explicitly, if needed, with "`r`n" and "`n"

    Caveat:

    The above -join solution implicitly converts the input objects to strings, if they aren't already and does so by calling the .NET .ToString() method on each object. This often yields a different representation than the one that Out-File would directly create, because Out-File uses PowerShell's default output formatter; for instance, compare the outputs of (Get-Date).ToString() and just Get-Date.

    If your input comprises only strings and/or non-strings whose .ToString() representation is satisfactory, the above solution works, but note that it is then generally preferable to use the Set-Content cmdlet, which applies the same stringification implicitly.
    For a complete discussion of the differences between Out-File and Set-Content, see this answer of mine.

    If your input has non-strings that do you want to be formatted as they would print to the console, there is actually no simple solution: while you can use Out-String to create per-object string representations with the default formatter, Out-String's lack of -NoNewline (as of v5.1; this GitHub issue suggests introducing it) would invariably yield trailing newlines.

提交回复
热议问题