Continuous Integration, Powershell

How to create and run a Powershell script

Presently my Visual Studio 2015 instance is out of commission because I’m installing Update 2 ahead of the Hololens Dev Kit and Emulator general release tomorrow, so I’ll write a simple post about something that doesn’t need VS2015.

I’ve spoken to a few other C# developers and recommended using Powershell scripts to assist with their continuous deployment. This post is meant to explain one of the simplest things with powershell scripting – how to run a script.

I normally run powershell scripts directly from an instance of Powershell. However, it’s normally necessary to change the computer’s execution policy to be able to run powershell scripts that I’ve created.

As an example, I created a trivial deployment script – the code below copies binaries from a project directory to a deployment directory.

Get-Childitem C:\ProjectDirectory\bin -recurse -filter "*.dll" | %{ Copy-Item -Path $_.FullName -Destination C:\DeploymentDirectory\root}

I saved this to a script called CopyBinaries.ps1.

When I open a powershell window, navigate to the script’s parent directory and run the command “./CopyBinaries.ps1“, I get an error telling me that the file “cannot be loaded because running scripts is disabled on this system“.

This is because the Execution Policy on my machine is set to Restricted, which means I’m not allowed to run any powershell scripts.

To change this, I need to change the execution policy to RemoteSigned. This changes my system to allow me to run powershell scripts that I’ve created locally (which I’m happy to do, because I trust these scripts), and scripts that I’ve downloaded which are digitally signed with the publisher’s identity. There’s more information on execution policies here.

I can change my local policy by running a powershell window as an administrator, and run the command:

Set-ExecutionPolicy RemoteSigned

This asks me to confirm that I intend to do this and understand the consequences – I just type Y to confirm and hit Enter. I can confirm my update to my local execution policy has succeeded by typing:

Get-ExecutionPolicy

Now if I repeat the process of navigating to the script’s parent directory and run the command “./CopyBinaries.ps1“, all binary DLL files are successfully copied from the “C:\ProjectDirectory\bin” to the “C:\DeploymentDirectory\root” directory.