Encode PowerShell Commands

by Aug 7, 2015

When you need to run code as a PowerShell command in a separate powershell.exe, it is not always safe to submit the code. Depending on from where you call powershell.exe, your code argument may get modified by parsers, or special characters inside your code confuse the host.

A more robust way to submit commands is to encode them and then submit the encoded command. This works for short code only. The length must be limited to roughly 8000 characters.

$code = {
  Get-EventLog -LogName System -EntryType Error |

$Bytes = [System.Text.Encoding]::Unicode.GetBytes($code.ToString()) 
$Encoded = [Convert]::ToBase64String($Bytes) 

$args1 = '-noprofile -encodedcommand ' + $Encoded

Start-Process -FilePath powershell.exe -ArgumentList $args1 

Twitter This Tip! ReTweet this Tip!