How to Create Files with Proper Names in PowerShell Scripts Using UTF-8?

0
10
Asked By TechieExplorer88 On

I'm working with a PowerShell script that includes the following line:

New-Item -Path "" -ItemType File

However, when I create a file on NTFS (Windows), its name appears as ``. My script is encoded in UTF-8, but I've noticed that saving it in UTF-16 BE resolves the issue. Is there a way to keep my script in UTF-8 while ensuring that files are created with the correct names on NTFS? Or do I need to convert all my scripts to UTF-16 for file handling on NTFS?

4 Answers

Answered By PowerShellPro On

Just save the script correctly in UTF-8 with BOM. That keeps the advantages of UTF-8 while avoiding any encoding confusion on NTFS.

Answered By BashFanatic99 On

Have you considered using UTF-8 with BOM? It can help resolve these encoding issues. Though personally, I’m not a big fan of BOM in text files—just from past experiences—but it does work.

Answered By CoderChick99 On

You could also modify your command to use: `New-Item -ItemType File -Path ([System.Web.HttpUtility]::HtmlDecode('ö'))`. This way, the encoding won't be an issue.

Answered By ScriptGuru42 On

The issue here is that Windows PowerShell v5.1 interprets `.ps1` files using the old ANSI code page (usually `Windows-1252` in English systems) when there's no BOM (Byte Order Mark). When your script is saved as UTF-8, `` gets split into two separate bytes. So, PowerShell reads each byte as individual characters instead of one. If you want to stick with UTF-8 without BOM, switch to PowerShell v7 or later. For now, you can save your script in UTF-8 with BOM or use the character's codepoint like this:

New-Item -Path ([char] 0xF6) -ItemType File

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.