Run a PowerShell script directly from GitHub Gist
Simple code that enables you to host your PowerShell scripts on GitHub Gist but execute them from a local machine.
When working with PowerShell scripts, I like to package them as .ps1 files and execute them from .bat files. As a back-up, I store my scripts on GitHub Gist, which has a utility to output code in a raw text format.
Running a PowerShell script from GitHub Gist
It is entirely possible to use PowerShell on a PC to execute .ps1 files hosted on GitHub Gist. Here’s how to do it:
Let’s say that a useful PowerShell script has been saved to https://gist.github.com/AdamDimech/08ba988211b55c71a480449b3b8ab6cd/. To execute this code, the raw-formatted version needs to be accessed, which is a simple case of adding /raw
to the end of the URL. (You will notice that gist.github.com redirects to gist.githubusercontent.com when raw files are accessed).
The raw file URL can be wrapped in code and executed in PowerShell as follows:
iex ((New-Object System.Net.WebClient).DownloadString('https://gist.githubusercontent.com/AdamDimech/08ba988211b55c71a480449b3b8ab6cd/raw'))
Accessing code from any other website would be equally possible as long as the code is provided as plain text and not formatted HTML.
The iex
command is actually a PowerShell alias for Invoke-Expression
.
Preparing batch files
If you were wishing to execute your code from a batch file, the code would appear as follows:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://gist.githubusercontent.com/AdamDimech/08ba988211b55c71a480449b3b8ab6cd/raw'))"
Save this code as a .bat file, which can then be used to execute the remote script. Note: GitHub Gist RAW files will take approximately three minutes to update when changes are made to the base code.
Comments
2 responses to “Run a PowerShell script directly from GitHub Gist”
Hey there I found very useful this post, is exactly what I need but I’m wondering how to supply arguments to the remote script: PowerShell -NoProfile -ExecutionPolicy Bypass -Command “iex ((New-Object System.Net.WebClient).DownloadString(‘https://gist.githubusercontent.com/AdamDimech/08ba988211b55c71a480449b3b8ab6cd/raw’))” -MyArgument HelloWorld
Exception calling “DownloadString” with “1” argument(s): “The request was aborted: Could not create SSL/TLS secure
channel.”
At line:1 char:1
+ iex ((New-Object System.Net.WebClient).DownloadString(‘https://gist.g …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
any thoughts as to why this cannot be ran? Or what I need to do to successfully create ssl tsl connection?\