Ironman Software Forums
Continue the conversion on the Ironman Software forums. Chat with over 1000 users about PowerShell, PowerShell Universal, and PowerShell Pro Tools.
In this post, we’ll look at how to embed assemblies in PowerShell as base64 strings.
Base64 is a ASCII representation of binary data. You can convert byte arrays in .NET into base64 strings and back again. Because of this, you can embed binary data into a PowerShell PS1 script as a simple text string.
To convert a byte array into a base64 string, you can use the
[byte]$Bytes = @(10, 11, 12) [Convert]::ToBase64String($Bytes) # CgsM
You can also use the
Convert class to do the opposite.
$Bytes = [Convert]::FromBase64String('CgsM') # 10 # 11 # 12
You can embed a .NET assembly directly in a PowerShell script and load it with the
First, convert the assembly to base64. This example uses NewtonSoft.Json.
$Bytes = [IO.File]::ReadAllBytes("NewtonSoft.Json.dll") $Base64 = [Convert]::ToBase64String($Bytes)
Next, in your PS1, you can include the base64 string directly in the code. Then, convert it back to bytes and load it with the assembly class.
$Base64 = "base64-string" $Bytes = [Convert]::FromBase64String($Base64) [System.Reflection.Assembly]::Load($Bytes)
Note that AMSI providers like PowerShell Protect may block scripts from loading assemblies in this manner.
Find this useful? Please consider sharing this article. Have a question about PowerShell? Contact us and we'll write a post about it.