Friday, February 22, 2013

PowerShell and TopShelf

Preface

A large part of our development involves generic services. TopShelf simplifies the installation and operation of the services we've been creating. When dealing with a number of services, it can still be a pain to install and start each individual service. To ease that pain point, we created a simple PowerShell script to help.

Deploying the Services

One project involved creating a set of services which were passing messages via RabbitMQ. Setting up a server (test or otherwise) involved dropping 3-6 services in a directory, configuring them, and starting them up. The deployment would be similar to the following:

/Parent Directory
    TopShelfHelper.ps1
    /ServiceA Directory
        topshelfhost.exe
        ... (Other Files)
    /ServiceB Directory
        topshelfhost.exe
        ... (Other Files)

The Script

The script is available on GitHub. Here it is for reference:

param(
 [parameter(mandatory=$true)]
 [validateset("start","stop","uninstall", "install")]
 $command
)

$ErrorActionPreference = "Stop"

push-Location

try
{
 get-ChildItem -Path $pwd -Recurse |
  where-Object {$_.name -eq 'topshelfhost.exe'} |
  select-Object fullname |
  foreach-object {& $_.fullname $command}

 "INFO: Operation completed successfully."
}
catch
{
 $Error[0]
 "ERROR: An error occurred performing the operation."
}
finally
{
 pop-Location
}

This script uses Get-ChildItem to look through all the directories in the current directory. When it finds the appropriate .exe file, it executes the TopShelf command on it. This example script uses the name 'topshelfhost.exe' to as the TopShelf enabled app.

Using the script is pretty easy. Just pass it one of the TopShelf commands (start, stop, install, uninstall), and it handles the rest. Here's an example...


Summary

Not the cleanest of scripts, but an example of you PowerShell can be used to ease some other tasks.

No comments:

Post a Comment