Power to the people

My esteemed colleague Jouni Heikniemi is a speaker at this year’s TechDays Finland. His topic is “PowerShell for Developers”. We had a chance to hear his presentation beforehand this morning. I’ve been meaning to do so for a few years now, but after the presentation I finally found the motivation to try and write an actual PowerShell script for myself.

The problem

I wanted a simple script to bundle an ASP.NET web application in a directory – basically, copy all the files that are essential to running the app, and nothing more. Something I’d typically use a NAnt or MSBuild task for.

The solution

image

So I fired up PowerShell ISE (I assume that’s Integrated Scripting Environment) and after a few attempts, came up with this:

$targetPath = "deploy"
if (Test-Path $targetPath) { Remove-Item $targetPath -Recurse -Force }

New-Item $targetPath -type directory

Copy-Item -Path .\App_Data -Destination $targetPath -Recurse 
Copy-Item -Path .\App_GlobalResources -Destination $targetPath -Recurse -Filter "*.resx"
Copy-Item -Path .\bin -Destination $targetPath -Recurse -Filter "*.dll"
Copy-Item -Path ("*.as?x", "*.js", "*.gif", "*.jpg", "Web.config") -Destination $targetPath

Since it creates a directory that can be deployed as an application, I saved the snippet as Deploy.ps1 (in hindsight, Build.ps1 would have been a better name, but I’m too lazy to take another screenshot).

This bit of script is very specific to my needs, so don’t take it as a textbook example of good PowerShell scripting. 🙂

The snag and the resolution

As it turns out, PowerShell scripts aren’t allowed to run, at all, by default. Fortunately, the default is relatively easy to change. Fire up PowerShell or the ISE with administrative privileges, and type:

Set-ExecutionPolicy RemoteSigned

RemoteSigned means you’re free to run unsigned scripts as long as they’re locally created, but scripts downloaded from other sources need to be signed. In case you’re curious, downloaded scripts are identified based on Alternate Data Streams.

PowerShell will ask you to confirm this. In the case of ISE, by means of a really, really long-ass dialog text:

image

Once you confirm the change, you can restart PowerShell with limited privileges, and scripts will work.

For more info on PowerShell, visit Jouni’s series of blog posts on the topic.

Leave a Reply

Your email address will not be published. Required fields are marked *