Decoding base64 with powershell

自作多情 提交于 2019-12-12 09:33:51

问题


I'm attempting to decode an attachment in an email file from base64 and save it to disk.

For testing purposes, this is my code. Where input.txt contains just the base64 encoded data, which is an HTML file.

$file = "C:\input.txt"
$data = Get-Content $file
[System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($data)) > out.html

The decoding works fine, and it generates a new file that contains all of the lines, and is visibly identical to the original attachment. The problem is that the output file is twice the size (actually (filesize*2)+6 bytes, in this case).

Am I decoding this improperly? I've also tried UTF8 instead of ASCII... same result.


回答1:


Well I got it working. Who knew Out-File re-encoded to Unicode by default? Solved by doing the following:

$file = "C:\input.txt"
$data = Get-Content $file
[System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($data)) | Out-File -Encoding "ASCII" out.html



回答2:


This one-liner preserves the original encoding of the base64 encoded file, so it will work with binary files such as a PDF or ZIP. Change ".\input.txt" and output.bin as needed - this will take .\input.txt, base 64 decode it, and then write the bytes out to output.bin exactly as they were when the file was encoded.

$file = ".\input.txt"; [System.Convert]::FromBase64String((Get-Content $file)) | Set-Content output.bin -Encoding Byte



回答3:


I know it's an old question, but i found another answer. You can use unicode at the base64 conversion, it will fit after.

$file = "C:\temp\input.txt"
$data = Get-Content $file
[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($data)) > out.html


来源:https://stackoverflow.com/questions/18726418/decoding-base64-with-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!