CodexBloom - Programming Q&A Platform

PowerShell 7.3 - advanced patterns When Using Set-Content to Write to a File with UTF-8 Encoding

๐Ÿ‘€ Views: 73 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-06
powershell encoding set-content PowerShell

I'm working with an scenario when trying to write a UTF-8 encoded string to a file using `Set-Content`. Despite specifying the `-Encoding UTF8` parameter, the output file contains garbled characters. Hereโ€™s a snippet of my code: ```powershell $content = "This is a test: ฯ€, ๐“ฌ, and ๐”ธ" Set-Content -Path "output.txt" -Value $content -Encoding UTF8 ``` After running the above command, I opened `output.txt`, and instead of seeing the expected characters, I found strange symbols and question marks instead. I've also tried using `Out-File` as follows: ```powershell $content = "This is another test: ฯ€, ๐“ฌ, and ๐”ธ" Out-File -FilePath "output2.txt" -InputObject $content -Encoding UTF8 ``` Unfortunately, the output remains the same. Iโ€™ve verified that my PowerShell console is set to use UTF-8 by running `$OutputEncoding`. The output of that command shows `System.Text.UTF8Encoding`, which seems correct. To debug further, I checked my systemโ€™s locale settings and ensured that my file system supports UTF-8. Iโ€™m running Windows 10 with PowerShell 7.3. I also tried the `-NoByteOrderMark` switch, but it hasn't resolved the scenario. Is there something I'm missing, or is there a known scenario with `Set-Content` in this version of PowerShell when handling UTF-8? Any guidance would be greatly appreciated!