By default, PowerShell in Windows seems to be outputting UTF-16 (e.g., if I do a simple echo hello > hi.txt, then hi.txt ends up in UTF-16). I know that I can force this to my desired text encoding by instead doing echo hello | out-file -encoding utf8 hi.txt, but what I'd like is for that to just be the default when I use the redirection operator. Is there any way to achieve this?
Asked
Active
Viewed 3.2k times
36
Benjamin Pollack
- 1,445
3 Answers
23
Using a .NET decompiler on the System.Management.Automation assembly (a.k.a. the "Microsoft Windows PowerShell Engine Core Assembly") reveals this code fragment:
// class: System.Management.Automation.RedirectionNode
private PipelineProcessor BuildRedirectionPipeline(string path, ExecutionContext context)
{
CommandProcessorBase commandProcessorBase = context.CreateCommand("out-file");
commandProcessorBase.AddParameter("-encoding", "unicode");
if (this.Appending)
{
commandProcessorBase.AddParameter("-append", true);
}
commandProcessorBase.AddParameter("-filepath", path);
...
So, it looks pretty hardcoded to me.
FYI, this was on Windows 7 Enterprise x64 system with PowerShell 2.0 installed.
Tinister
- 348
3
You need to change the default encoding of redirection operators (> and >>). The Out-File cmdlet is used behind the scenes when you use these operators.
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
See Powershell Docs for details.
Yura Loginov
- 131
3
Not sure if this will do exactly what you're looking for, but you can try setting the environment variable as mentioned here
$OutputEncoding = New-Object -typename System.Text.UTF8Encoding
Glorfindel
- 4,158
OldWolf
- 2,493