Skip to main content

PowerShell function to write a file using UTF8 (no BOM) encoding.

function Out-Utf8File
{
    <#
    .DESCRIPTION
        Writes a file using UTF8 (no BOM) encoding.

    .PARAMETER Path
        The path to the file to write to.

    .PARAMETER Content
        The string content for the file.

    .PARAMETER Force
        Indicates that this should overwrite an existing file that has the
        same name.

    .INPUTS
        String

    .EXAMPLE
        Out-Utf8File -Path ./foo.txt -Content 'bar'
        Creates a 'foo.txt' in the current working directory with the content
        'bar' as a UTF-8 file without BOM.

    .NOTES
        This is being used because the PS5 Encoding options only include utf8
        with BOM, and we want to write without BOM.  This is fixed in PS6+,
        but we need to support PS4+.

    .LINK
        https://github.com/microsoft/PowerShellForGitHub/blob/master/build/scripts/Build-Wiki.ps1#L61
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string] $Path,

        [Parameter(ValueFromPipeline)]
        [string] $Content,

        [switch] $Force
    )
    begin
    {
        if (Test-Path -Path $Path -PathType Leaf)
        {
            if ($Force.IsPresent)
            {
                Remove-Item -Path $Path -Force | Out-Null
            }
            else
            {
                throw "[$Path] already exists and -Force was not specified."
            }
        }

        $stream = New-Object -TypeName System.IO.StreamWriter -ArgumentList ($Path, [System.Text.Encoding]::UTF8)
    }
    process
    {
        $stream.WriteLine($Content)
    }
    end
    {
        $stream.Close();
    }
}

# Example usage:
$newline = [System.Environment]::NewLine

$content = ("{0}$newline{1}$newline{2}" -f
    "First line in file.",
    "Second line in file.",
    "Third line in file."
)

Out-Utf8File -Path "utf8-no-bom.txt" -Content $content -Force