title: Encode / Decode .EXE into Base64
body: <p>I have a .NET exe file that I'd like to encode into a Base-64 string, and then at a later point decode into a .exe file from the Base64 string, using Powershell.</p>
  
  <p>What I have so far <strong>produces a .exe file</strong>, however, the file isn't recognizable to windows as an application that can run, and is always a different length than the file that I'm passing into the encoding script.</p>
  
  <p>I think I may be using the wrong encoding here, but I'm not sure.</p>
  
  <p><strong>Encode script:</strong></p>
  
  <pre><code>Function Get-FileName($initialDirectory)
  {   
   [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
  $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
  $OpenFileDialog.initialDirectory = $initialDirectory
  $OpenFileDialog.filter = "All files (*.*)| *.*"
  $OpenFileDialog.ShowDialog() | Out-Null
  $FileName = $OpenFileDialog.filename
  $FileName
  
  } #end function Get-FileName
  
  $FileName = Get-FileName
  
  $Data = get-content $FileName
  $Bytes = [System.Text.Encoding]::Unicode.GetBytes($Data)
  $EncodedData = [Convert]::ToBase64String($Bytes)
  </code></pre>
  
  <p><strong>Decode Script:</strong></p>
  
  <pre><code>$Data = get-content $FileName
  $Bytes = [System.Text.Encoding]::UTF8.GetBytes($Data)
  $EncodedData = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Bytes))
  
  $EncodedData | Out-File ( $FileName )
  </code></pre>