Occasionally, PowerShell scripts are made available via direct download. Let’s find the most efficient way to download text-based files via PowerShell. We’ll use the famous “Dancing Rick ASCII” script published by PowerShell Team member Lee Holmes for our examples. It is located here:

http://bit.ly/e0Mw9w

When opened in a browser, you’ll see the PowerShell source code as plain text, and the original URL is shown in the browser bar:

http://www.leeholmes.com/projects/ps_html5/Invoke-PSHtml5.ps1

Many users resort to .NET methods to download text files like this:

# download code
$url = "http://bit.ly/e0Mw9w"
$webclient = New-Object Net.WebClient
$code = $webclient.DownloadString($url)

# output code
$code

There is no need for this, though, because Invoke-WebRequest is a convenient wrapper around that object:

# download code
$url = "http://bit.ly/e0Mw9w"
$page = Invoke-WebRequest -Uri $url -UseBasicParsing
$code = $page.Content

Via its parameters, it includes proxy support and support for credentials right out of the box.

There’s an even more convenient cmdlet calling Invoke-RestMethod. It basically does the same but returns the data as text, JSON, or XML:

# download code
$url = "http://bit.ly/e0Mw9w"
$code = Invoke-RestMethod -Uri $url -UseBasicParsing

Provided you are confident that the code is legit and won’t harm your system, you can now invoke it:

# invoke the code
Invoke-Expression -Command $code

Or, you can save it to disk and run it as a regular PowerShell script:

# download code
$url = "http://bit.ly/e0Mw9w"
$code = Invoke-RestMethod -Uri $url -UseBasicParsing 

# save to file and run
$outPath = "$home\Desktop\dancingRick.ps1"
$code | Set-Content -Path $outPath -Encoding UTF8
Start-Process -FilePath powershell -ArgumentList "-noprofile -noexit -executionpolicy bypass -file ""$outPath"""

If you plan to download the content to a file in the first place, then Invoke-WebRequest is the better choice because it can save contents directly to file:

# download code
$url = "http://bit.ly/e0Mw9w"
$outPath = "$home\Desktop\dancingRick.ps1"
$code = Invoke-WebRequest -Uri $url -UseBasicParsing -OutFile $outPath
& $outPath

You can run the downloaded file directly in your own PowerShell session by using the call operator (&), rather than using Start-Process. If this fails, most likely your execution policy does not allow PowerShell scripts to be run. Change the setting like so, then try again:

 
PS> Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned 
 

Twitter This Tip! ReTweet this Tip!

Anonymous