powershell 如何在不改变编码的情况下将命令的输出通过管道传输到文件?

pxy2qtax  于 2023-03-23  发布在  Shell
关注(0)|答案(4)|浏览(110)

我想将命令的输出通过管道传输到一个文件:

PS C:\Temp> create-png > binary.png

我注意到PowerShell改变了编码,我可以手动给予一个编码:

PS C:\Temp> create-png | Out-File "binary.png" -Encoding OEM

然而,没有RAW编码选项,即使OEM选项也会将换行符字节(0xA resp 0xD)更改为Windows换行符字节序列(0xD 0xA),从而破坏任何二进制格式。
如何防止Powershell在管道传输到文件时更改编码?

相关问题

vwkv1x7d

vwkv1x7d1#

尝试使用set-content:

create-png | set-content -path myfile.png -encoding byte

如果您需要有关set-content的其他信息,只需运行

get-help set-content

您也可以使用'sc'作为set-content的快捷方式。
使用以下内容进行测试,生成可读的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),并且您只想从标准输出中捕获字节,请尝试Start-Process:

Start-Process -NoNewWindow -FilePath 'ipconfig' -RedirectStandardOutput 'output.dat'
xdnvmnnf

xdnvmnnf2#

创建包含该行的批处理文件

create-png > binary.png

并通过以下方式从Powershell调用

& cmd /c batchfile.bat

如果您更愿意将命令作为命令行参数传递给cmd:

$x = "create-png > binary.png"
& cmd /c $x
ohtdti5x

ohtdti5x3#

根据this well written blog article
在PowerShell中使用curl时,永远不要使用〉重定向到文件。始终使用-o或-out开关。如果您需要将curl的输出流式传输到另一个实用程序(例如gpg),那么您需要将子shell转换为cmd以进行二进制流式传输或使用临时文件。

jgzswidk

jgzswidk4#

Powershell将输出视为字符串。但windows-1252将每个字节Map为字符,您可以尝试使用此编码。
这是一个诡计,虽然它不是有效的。
在我的例子中,powershell版本是5.1,Out-File或〉操作符不支持windows 1252,所以我必须使用WriteAllText方法。例如:

[console]::outputencoding=[console]::inputencoding=[System.Text.Encoding]::GetEncoding(1252)
$result=python zipbomb --mode=quoted_overlap --num-files=250 --compressed-size=21179
[IO.File]::WriteAllText("$pwd\result.zip",$result,[System.Text.Encoding]::GetEncoding(1252))

或简单地使用带有-RedirectStandardOutput选项的Start-Process

Start-Process -FilePath "python.exe" -ArgumentList "zipbomb --mode=quoted_overlap --num-files=250 --compressed-size=21179" -RedirectStandardOutput output.zip

相关问题