I need to remove BOM using cmd file from MyFile.txt. The file is located here.
“| Out-File -encoding utf8 ‘%CD%MyFile.txt'”
I need it to be removed using only one cmd, that is, in the next lines. I need it to be backwards compatible to Windows 7. If I needed it for myself only I would just use -encoding default, but its not backwards compatible even to win 10. Just one file. There were many different questions about BOM on different situations, my issue is I need to use one .cmd, I already have utf8 with BOM and I need it without BOM. Please help me.
I was trying to use powershell but the issue is powershell syntax is not really compatible to cmd? It just says about unrecognised syntax everytime I tried anything from the very popular theme like this Using PowerShell to write a file in UTF-8 without the BOM. So I need help really desperately.
Verity Freedom is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
PowerShell is indeed your best bet, and while you cannot directly use PowerShell commands from cmd.exe
/ a batch file, you can pass them to powershell.exe
, the Windows PowerShell CLI:
@echo off & setlocal
set "targetFile=%CD%MyFile.txt"
powershell -noprofile -c New-Item $env:targetFile -Force -Value (Get-Content -Raw -LiteralPath $env:targetFile)
Note:
-
The PowerShell code takes advantage of the fact that
New-Item
, when given a-Value
argument, creates a BOM-less UTF-8 file, even in Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1) – see this answer for details. -
Caveat: By reading the entire file into memory first, with
Get-Content
-Raw
and rewriting it in full – with BOM-less UTF-8 encoding – there is a hypothetical risk of data loss, however unlikely: if rewriting the file’s content gets interrupted, say due to a power outage, data loss may occur.-
To eliminate this risk, you’d have to write to a temporary file first, and then, once the temporary file was successfully written, replace the original file with it.
-
Similarly, you’d need a temporary file if the input file is too large to fit into memory as a whole (which is not typical for text files); in that case, you can combine
[IO.File]::ReadLines()
with[IO.File]::WriteAllLines()
to read and write line by line.
-