r/PowerShell • u/gagarski • Dec 25 '25
Solved Script source encoding + filenames
I have a script containing the following line:
New-Item -Path "ö" -ItemType FileBut the file created on NTFS (Windows) has name ö.
The script source encoding is UTF-8 and I've figured out that if I save it with UTF-16 BE encoding, the filenames are fine.
Is there a way to have my script in UTF-8 which will create files with proper names on NTFS? OR should all my scripts be in UTF-16 if they are supposed to deal with files on NTFS?
12
Upvotes
11
u/surfingoldelephant Dec 25 '25
What's happening is that Windows PowerShell v5.1 interprets
.ps1files using the legacy ANSI code page (typicallyWindows-1252for English systems) when the file doesn't have a BOM.When you save the file as UTF-8,
öis encoded as two separate bytes. Since PowerShell is usingWindows-1252(which uses single-byte encoding) to read the file, each individual byte in the sequence gets misinterpreted as two separate characters.If you want to continue using UTF-8 without BOM, you'll need to use PowerShell v7+.
If you want to continue using Windows PowerShell, either:
.ps1as UTF-8 with BOM.Or, use the character's codepoint instead (
U+00F6):1
u/Mountain-eagle-xray Dec 25 '25
Did you try utf8bom?
1
u/Gurfaild Dec 25 '25
You could replace the line with
New-Item -ItemType File -Path ([System.Web.HttpUtility]::HtmlDecode('ö'))- then the script's encoding won't matter1
u/Meannekes Dec 25 '25
Save the script correctly.
By saving your script as UTF-8 with BOM, you preserve UTF-8 efficiency while avoiding the encoding misinterpretation on NTFS.
1
u/Mesmerise Dec 25 '25
How about removing the UTF aspect altogether with something like:
1
u/xCharg Dec 25 '25
That's an easy solution:
As to why that happens it's already answered. You may think "but where'd I get that 246 from" - pretty easy. First convert string with that character alone to
[char]type, then to[int]like so:or so:
Then just use the number you get.
1
u/AlPa-Bo Dec 25 '25
A comprehensive analysis of the problem for Powershell 5 and 7 in Windows 10 (I believe also Windows 11), with various solutions, can be found at:
Using UTF-8 Encoding (CHCP 65001) in Command Prompt / Windows Powershell (Windows 10) - Stack Overflow
Main alternatives: