Run a .Net Assembly DLL from Memory in PowerShell

In my previous post I showed you how to load a .NET Assembly DLL without registering in the GAC.

Using the technique found here you can run the .NET Assembly DLL from Memory !

Run this script from the above site using your new .NET DLL (see my previous post).

CLS

function Out-CompressedDll
{
    [CmdletBinding()] Param (
        [Parameter(Mandatory = $True)]
        [String]
        $FilePath
    )

    $Path = Resolve-Path $FilePath

    if (! [IO.File]::Exists($Path))
    {
        Throw "$Path does not exist."
    }

    $FileBytes = [System.IO.File]::ReadAllBytes($Path)

    if (($FileBytes[0..1] | % {[Char]$_}) -join '' -cne 'MZ')
    {
        Throw "$Path is not a valid executable."
    }

    $Length = $FileBytes.Length
    $CompressedStream = New-Object IO.MemoryStream
    $DeflateStream = New-Object IO.Compression.DeflateStream ($CompressedStream, [IO.Compression.CompressionMode]::Compress)
    $DeflateStream.Write($FileBytes, 0, $FileBytes.Length)
    $DeflateStream.Dispose()
    $CompressedFileBytes = $CompressedStream.ToArray()
    $CompressedStream.Dispose()
    $EncodedCompressedFile = [Convert]::ToBase64String($CompressedFileBytes)

    Write-Verbose "Compression ratio: $(($EncodedCompressedFile.Length/$FileBytes.Length).ToString('#%'))"

    $Output = @"
`$EncodedCompressedFile = @'
$EncodedCompressedFile
'@
`$DeflatedStream = New-Object IO.Compression.DeflateStream([IO.MemoryStream][Convert]::FromBase64String(`$EncodedCompressedFile),[IO.Compression.CompressionMode]::Decompress)
`$UncompressedFileBytes = New-Object Byte[]($Length)
`$DeflatedStream.Read(`$UncompressedFileBytes, 0, $Length) | Out-Null
[Reflection.Assembly]::Load(`$UncompressedFileBytes)
"@

    Write-Output $Output
}

# See Example on the site
# Out-CompressedDll .\test.dll | Out-File LoadDll.ps1

Out-CompressedDll "C:\\_\\Apps\\Hello World.dll" | Out-File .\LoadDll.ps1

Invoke-Item ($Env:USERPROFILE+"\LoadDll.ps1")

This will generate a new PS1 Script which will contain the compressed DLL code as a binary string.

image

Add your static method to call whatever you specified in your DLL.

image

Run it to see that is works.

So bottom line is that you don’t need to register in the GAC and don’t need to copy the DLL to your machines in order to run it Smile

Isn’t that great for a scripter !

Advertisements

One Response to Run a .Net Assembly DLL from Memory in PowerShell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: