Run a PowerShell script directly from GitHub Gist
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.
iex command is actually a PowerShell alias for
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.