Using Encoded Scripts

by Sep 29, 2015

In VBScript there were encoded scripts. Encoding is by no means a safe way of hiding script content, but it makes it a little harder for users to touch the code.

Here is a function that takes a PowerShell script and encodes it:

function ConvertTo-EncodedScript
{
  param
  (
    $Path,
    
    [Switch]$Open
  )
  
  $Code = Get-Content -Path $Path -Raw
  $Bytes = [System.Text.Encoding]::Unicode.GetBytes($Code) 
  $Base64 = [Convert]::ToBase64String($Bytes) 
  
  $NewPath = [System.IO.Path]::ChangeExtension($Path, '.pse1')
  $Base64 | Set-Content -Path $NewPath

  if ($Open) { notepad $NewPath }
}

The encoded script will be saved in a file with the extension .pse1 (which is a completely arbitrary file extension and not defined by Microsoft).

To actually run the encoded script, run this command (not from within the PowerShell ISE though):

powershell -encodedcommand (Get-Content 'Z:\pathtoscript\scriptname.pse1' -Raw)

Note that PowerShell supports encoded commands to a maximum length of approximately 8000 characters. The orignal purpose of encoded commands is to safely submit PowerShell code to powershell.exe without the risk of special characters breaking the command line.

Twitter This Tip! ReTweet this Tip!