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:

    To spell out the solution based on the linked answer:

    # Download the file as a byte[] array.
    $bytes = (Invoke-WebRequest "http://example.com/path/to/binary.exe").Content
    
    # Load the byte array as an assembly.
    $assembly = [System.Reflection.Assembly]::Load($bytes)
    
    # Get the static "Main" method that is the executable's entry point,
    # assumed to be a member of a "Program" class.
    $entryPointMethod = 
     $assembly.GetTypes().Where({ $_.Name -eq 'Program' }, 'First').
       GetMethod('Main', [Reflection.BindingFlags] 'Static, Public, NonPublic')
    
    # Invoke the entry point.
    # This example passes two arguments, 'foo' and 'bar'
    $entryPointMethod.Invoke($null, (, [string[]] ('foo', 'bar')))
    

    Note: