问题描述
我想将命令的输出传递给文件:
I want to pipe the output of a command to a file:
PS C:\Temp> create-png > binary.png
我注意到Powershell更改了编码,我可以手动进行编码:
I noticed that Powershell changes the encoding and that I can manually give an encoding:
PS C:\Temp> create-png | Out-File "binary.png" -Encoding OEM
但是,没有RAW编码选项,即使OEM选项也将换行符字节(0xA
resp 0xD
)更改为Windows换行符字节序列(0xD 0xA
),从而破坏了任何二进制格式.
However there is no RAW encoding option, even the OEM option changes newline bytes (0xA
resp 0xD
) to the windows newline byte sequence (0xD 0xA
) thereby ruining any binary format.
在传递到文件时,如何防止Powershell更改编码?
How can I prevent Powershell from changing the encoding when piping to a file?
相关问题
- PowerShellscript, bad file encoding conversation
- Write output to a text file in PowerShell
- Using PowerShell to write a file in UTF-8 without the BOM
推荐答案
尝试使用set-content:
Try using set-content:
create-png | set-content -path myfile.png -encoding byte
如果您需要有关设置内容的其他信息,请运行
If you need additional info on set-content just run
get-help set-content
您也可以将'sc'用作设置内容的快捷方式.
You can also use 'sc' as a shortcut for set-content.
经过以下测试,会生成可读的PNG:
Tested with the following, produces a readable PNG:
function create-png()
{
[System.Drawing.Bitmap] $bitmap = new-object 'System.Drawing.Bitmap'([Int32]32,[Int32]32);
$graphics = [System.Drawing.Graphics]::FromImage($bitmap);
$graphics.DrawString("TEST",[System.Drawing.SystemFonts]::DefaultFont,[System.Drawing.SystemBrushes]::ActiveCaption,0,0);
$converter = new-object 'System.Drawing.ImageConverter';
return([byte[]]($converter.ConvertTo($bitmap, [byte[]])));
}
create-png | set-content -Path 'fromsc.png' -Encoding Byte
如果您要调用非PowerShell可执行文件(如ipconfig),并且只想从标准输出中捕获字节,请尝试启动过程:
If you are calling out to a non-PowerShell executable like ipconfig and you just want to capture the bytes from Standard Output, try Start-Process:
Start-Process -NoNewWindow -FilePath 'ipconfig' -RedirectStandardOutput 'output.dat'
这篇关于如何在不通过Powershell更改编码的情况下将命令的输出通过管道传输到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!