Best way to prevent PS from adding BOM and newlines to output?

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Paal Braathen Paal Braathen 6 months ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #36828
    Profile photo of Paal Braathen
    Paal Braathen
    Participant

    Hi

    If you run

    Out-File -InputObject "A" -FilePath "test.txt"

    you will get both a BOM at the start of the file and a windows-newline at the end of the file. The same happens with Set-Content.

    How can I prevent this from happening? What is the best way to output a string, and only the string, to a file?

    If your string is plain ASCII I've noticed that you could do this in PowerShell5 (no -NoNewline in PowerShellS4)

    Out-File -InputObject "A" -FilePath "test.txt" -Encoding "ascii" -NoNewline

    but this does not help much if you have something outside of ASCII.

    #36847
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    This is one of those things that PowerShell doesn't really help you do, but you can do with the underlying .NET framework very easily. What you want is UTF8 encoding without a BOM, and to get that, you use the default constructor of the UTF8Encoding class:

    $encoding = New-Object System.Text.UTF8Encoding
    [System.IO.File]::WriteAllText("$pwd\test.txt", "Testing", $encoding)
    

    PowerShell's cmdlets, unfortunately, don't take an actual Encoding object. Instead, they take an enumerated type that's meant to be more user friendly (with tab completion and whatnot).

    When calling the .NET methods directly, just be careful not to send in any relative paths. The .NET framework's idea of your "current directory" is different from what PowerShell uses for its PSDrives. Here's how you can safely translate an arbitrary PSPath into one that's safe for .NET (even if the path doesn't already exist):

    $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($somePath)
    

    You can also use Resolve-Path, but unfortunately, that will fail if the item doesn't exist yet.

    #36852
    Profile photo of Paal Braathen
    Paal Braathen
    Participant

    Not the pretties thing I've seen, but it works 🙂 Thanks

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.