PowerShell - Batch change files encoding To UTF-8 PowerShell - Batch change files encoding To UTF-8 powershell powershell

PowerShell - Batch change files encoding To UTF-8


You didn't follow the whole answer in here. You forgot the WriteAllLines part.

$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)foreach ($i in Get-ChildItem -Recurse) {    if ($i.PSIsContainer) {        continue    }    $dest = $i.Fullname.Replace($PWD, "some_folder")    if (!(Test-Path $(Split-Path $dest -Parent))) {        New-Item $(Split-Path $dest -Parent) -type Directory    }    $content = get-content $i     [System.IO.File]::WriteAllLines($dest, $content, $Utf8NoBomEncoding)}


Half of the answer is in the error message. It tells you the possible values the Encoding parameter accepts, one of them is utf8.

... out-file -encoding utf8


I've made some fixes

  • Get-Childitem acts on $source
  • replace does not try to interpret $source as regex
  • some resolve-path
  • auto-help

and packaged everything into a cmdlet:

<#    .SYNOPSIS        Encode-Utf8    .DESCRIPTION        Re-Write all files in a folder in UTF-8    .PARAMETER Source        directory path to recursively scan for files    .PARAMETER Destination        directory path to write files to #>[CmdletBinding(DefaultParameterSetName="Help")]Param(   [Parameter(Mandatory=$true, Position=0, ParameterSetName="Default")]   [string]   $Source,   [Parameter(Mandatory=$true, Position=1, ParameterSetName="Default")]   [string]   $Destination,  [Parameter(Mandatory=$false, Position=0, ParameterSetName="Help")]   [switch]   $Help   )if($PSCmdlet.ParameterSetName -eq 'Help'){    Get-Help $MyInvocation.MyCommand.Definition -Detailed    Exit}if($PSBoundParameters['Debug']){    $DebugPreference = 'Continue'}$Source = Resolve-Path $Sourceif (-not (Test-Path $Destination)) {    New-Item -ItemType Directory -Path $Destination -Force | Out-Null}$Destination = Resolve-Path $Destination$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)foreach ($i in Get-ChildItem $Source -Recurse -Force) {    if ($i.PSIsContainer) {        continue    }    $path = $i.DirectoryName.Replace($Source, $Destination)    $name = $i.Fullname.Replace($Source, $Destination)    if ( !(Test-Path $path) ) {        New-Item -Path $path -ItemType directory    }    $content = get-content $i.Fullname    if ( $content -ne $null ) {        [System.IO.File]::WriteAllLines($name, $content, $Utf8NoBomEncoding)    } else {        Write-Host "No content from: $i"       }}