31

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?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Jeroen
  • 313
  • 1
  • 3
  • 5

1 Answers1

65

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)
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • It just worked like anything for me.. I was struggling for hours.. Thank you boss. – Amnesh Goel May 05 '17 at 12:51
  • 3
    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"` – Origin Aug 15 '17 at 09:59
  • 2
    Don't make the same mistake I did, `WriteAllBytes` will fail silently unless given an absolute path – jkmartindale Jul 14 '21 at 16:08
  • @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 Sep 28 '21 at 13:23
  • The process' current directory can be found with this call: [System.IO.Directory]::GetCurrentDirectory() – Peter Lindgren Sep 28 '21 at 13:31
  • WriteAllBytes does fail when param is relative. It's just that it writes the file to a directory other than the working directory. For me it was what is known in Linux as $HOME (/users/me/ in windows) – steve Oct 19 '22 at 19:45