Search code examples
powershellexecutableshellexecute

Executing Executables In Memory With Powershell


I have an executable on an internet page and I want to be able to run it without saving it to the local disk using powershell. It should basically function like iex but run an executable that's already in the memory and stored in some kind of variable. And again, I want to do all of that in Powershell.

Example.

(New-Object System.Net.WebClient).DownloadString("http://example.com") | iex

Here we can download scripts and run them in the memory without saving anything to the disk. But it's only a sequence of characters that we're executing here. Basically a powershell script. I want to run executables the same way. Is that possible? If so, how?


Solution

  • First, use Invoke-WebRequest to download your binary executable's content as a byte array ([byte[]]):

    $bytes = (Invoke-WebRequest "http://example.com/path/to/binary.exe").Content
    

    Then, assuming that the executable is a (compatible) .NET application:

    • Use .NET's ability to load an assembly from a byte array, then use reflection to directly execute this in-memory representation of your binary executable.
    • This answer shows the technique (based on a Base64-encoding string serving as the source of the byte array, but you can simply substitute your $bytes array in the linked code).