Friday, February 22, 2013

PowerShell and TopShelf


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
    /ServiceA Directory
        ... (Other Files)
    /ServiceB Directory
        ... (Other Files)

The Script

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

 [validateset("start","stop","uninstall", "install")]

$ErrorActionPreference = "Stop"


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

 "INFO: Operation completed successfully."
 "ERROR: An error occurred performing the operation."

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...


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