CodexBloom - Programming Q&A Platform

PowerShell 7.3 - advanced patterns with Out-File and UTF-8 Encoding for Special Characters

👀 Views: 1 💬 Answers: 1 📅 Created: 2025-06-10
powershell encoding utf-8 PowerShell

I'm having trouble with I've been banging my head against this for hours. I'm trying to write a PowerShell script that generates a report and saves it as a UTF-8 encoded text file. However, I'm running into an scenario where special characters (like accented letters) are not being saved correctly. I used the `Out-File` cmdlet with the `-Encoding UTF8` parameter, but when I open the file, the special characters appear as garbled text or question marks. Here is the code I've been using: ```powershell $data = @( "Name: José" "Age: 30" "Country: España" ) $data | Out-File -FilePath "C:\Reports\report.txt" -Encoding UTF8 ``` When I check the contents of `report.txt`, it looks something like this: ``` Name: Jos? Age: 30 Country: Espana ``` I've also tried using `Set-Content` with the same encoding, but the result is the same. I verified that my PowerShell session is set to use UTF-8 by checking `$OutputEncoding`, which returns `System.Text.UTF8Encoding`. ```powershell $OutputEncoding ``` This seems to be a common scenario when dealing with special characters in PowerShell, but I need to find a reliable solution. I've read that sometimes the `-Encoding` parameter does not work as expected with certain cmdlets, and it might depend on the text editor I use to open the file. Could anyone guide to understand how to ensure that special characters are correctly written and displayed in the text file? Are there specific editors or settings I should be aware of when viewing the output file? I'm working on a service that needs to handle this. Thanks in advance!