Wednesday, April 27, 2016

Running a program from the Internet on the command line

Attempting to use the Run dialog to start an EXE from the Internet usually results in your default browser opening and downloading the file, as opposed to it being downloaded by Windows and run.

Therefore, if you want to download and run an EXE, you'll need to do a little bit of scripting. PowerShell's Invoke-WebRequest is great for downloading things; WriteAllBytes can write the result to a file. Using those and some other little things, I composed this batch file that invokes PowerShell to accomplish the task.

@echo off
powershell -command $tmpPath = [System.IO.Path]::GetTempFileName() + '.exe'; 
 [System.IO.File]::WriteAllBytes($tmpPath, (Invoke-WebRequest "%*").Content);
 Start-Process $tmpPath

(The last three lines are actually one line, part of the arguments to powershell. Make sure you remove the line breaks.) The script finds a temporary file name (in the Temp directory), saves the EXE as it, and then runs it. The file isn't deleted after that, but since it's in Temp, it should get cleaned up eventually by disk cleanup tools. If you're not OK with that, you'll want to adjust the PowerShell part so that it waits for the executable to complete (use iex instead of Start-Process) and deletes it.

To use, save all that as a batch file and invoke it with a single parameter, the URL to execute.

Based on a Super User answer.

No comments:

Post a Comment