Convert base64 string to file

31,569

The FromBase64String() method converts a base64-encoded string to a byte array. All you need to do is write that byte array back to a file:

$b64      = 'AAAAAA...'
$filename = 'C:\path\to\file'

$bytes = [Convert]::FromBase64String($b64)
[IO.File]::WriteAllBytes($filename, $bytes)
Share:
31,569

Related videos on Youtube

Jeroen
Author by

Jeroen

Updated on February 11, 2020

Comments

  • Jeroen
    Jeroen about 4 years

    I'm trying to convert base64 strings back to the original files. The application from where I try to export these files will only allow me to export in base64 strings. This export returns the base64 string and the filetype.

    How can I convert these strings back to the original files? I've been trying things like this, but I don't think this will work with different types of files?

    [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($file)) |
        Out-File C:\ID\document.$($extension)
    

    Can anyone provide me some ideas on how to do this?

  • Amnesh Goel
    Amnesh Goel almost 7 years
    It just worked like anything for me.. I was struggling for hours.. Thank you boss.
  • Origin
    Origin over 6 years
    In my case, the Base-64 text was too long to paste into the powershell window, so I had to do $b64 = Get-Content "filePath"
  • jkmartindale
    jkmartindale almost 3 years
    Don't make the same mistake I did, WriteAllBytes will fail silently unless given an absolute path
  • Peter Lindgren
    Peter Lindgren over 2 years
    @jkmartindale I'd guess that it wrote all the bytes to the Powershell.exe's process Win32 current directory, which is not necessarily the same as Powershell's current location. The System.IO methods all use the current process' current directory for relative paths. Try search for it in your System32 folder.
  • Peter Lindgren
    Peter Lindgren over 2 years
    The process' current directory can be found with this call: [System.IO.Directory]::GetCurrentDirectory()