Executing a powershell script stored as a gist
- coding
- 2020-11-07
- 2 minutes to read
This post is over 24 months old, that is an lifetime in tech! Please be mindful of that when reading this post as it could be outdated. I try to keep on top of changes where possible. I try to keep things up to date, but if you think something needs updating, please let me know in the comments.
Introduction
I have been using Chocolatey to manage standard software builds for freshly created virtual machines (VM). I use a Mac and that requires me to stand up a Windows VM from time to time (cough Power BI) or I may want to run a SQL Server VM on Azure. Chocolatey allows me to preserve disk space by giving me the ability to writing a config script which I can fire up on a fresh VM and Chocolatey will proceed to download and install all defined software. This gives me the ability to create a VM, fire off a config, do some work and then clean up afterwards.
At some point I will write up some posts on Chocolatey as it’s a real time saver.
Objective
I have configured my build scripts as Powershell scripts because they install Chocolatey first. This allows me to run the build on a vanilla Windows VM. At present I copy the script to the VM and execute it. The objective is to avoid having to copy the file. My chocolatey scripts are hosted on github, so what I want to do is define a script that will execute the remote script. It’s worth noting, Chocolatey has the ability to fire configs stored as gists (does it? I am sure it does, I will confirm this) but that requires you to have Chocolatey installed first. Using this approach I can fire this on a vanilla VM, have chocolatey install and then install all remaining software.
Building the command
I have placed a gist at that simply writes “Hello World” to the console here;
https://gist.github.com/justinjbird/9118a3a5dfdecad19492b3e8ad54f81f
In order to use it in our command we need to get the plain text version. If we add /raw to the end of the URL this will present us with just that;
https://gist.github.com/justinjbird/9118a3a5dfdecad19492b3e8ad54f81f/raw
So now that we have defined that, we can fire the gist using Invoke-Expression ;
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://gist.github.com/justinjbird/9118a3a5dfdecad19492b3e8ad54f81f/raw'))
And there you have it!
So changing the URL for my chocolatey script gist, I can now copy and paste the command straight into the command line and kick off my automated builds. There is probably more I can do to automate this, still learning as I go!