PowerShell - Batch change files encoding To UTF-8
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 adapted few snipplets when I needed to UTF8 encode a massive amount of log-files.
Note! Should not be used with -recurse
write-host " "
$sourcePath = (get-location).path # Use current folder as source.
# $sourcePath = "C:\Source-files" # Use custom folder as source.
$destinationPath = (get-location).path + '\Out' # Use "current folder\Out" as target.
# $destinationPath = "C:\UTF8-Encoded" # Set custom target path
$cnt = 0
write-host "UTF8 convertsation from " $sourcePath " to " $destinationPath
if (!(Test-Path $destinationPath))
{
write-host "(Note: target folder created!) "
new-item -type directory -path $destinationPath -Force | Out-Null
}
Get-ChildItem -Path $sourcePath -Filter *.txt | ForEach-Object {
$content = Get-Content $_.FullName
Set-content (Join-Path -Path $destinationPath -ChildPath $_) -Encoding UTF8 -Value $content
$cnt++
}
write-host " "
write-host "Totally " $cnt " files converted!"
write-host " "
pause
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)
}