Tuesday, September 18, 2012

Welcome to Powershell Workflows. Please Follow These Rules

The most powerful feature introduced in Powershell 3.0 is The Workflow, no doubt. However, workflows are not something exclusive to Powershell. In fact, workflows (that is, the Windows Workflow Foundation) have been around since .NET 3.0 (recall that Powershell 3.0 requires .NET 4.0). When you are using workflows in Powershell, you have left the well-known comforts of Powershell. You are now a guest in the Windows Workflow Foundation.

Activites, not Commands
In each workflow you write, the individual lines are no longer commands. They are individual Activities, as per the Windows Workflow vocabulary. As such, they run in their own process. The implications here are great. For the sake of brevity, I'm only covering the cases that have occupied most of my time.

No Module Imports
Import-Module is one of the (many) disallowed cmdlets in workflows. In order to get around this, we have been given the -PSRequiredModule parameter.

Not this:
Import-Module AwesomeSauce
Import-Module RequiredModule
$goods = Get-OutTheGreat

This:
$goods = Get-OutTheGreat -PSRequiredModules 'AwesomeSauce','RequiredModule'

Snap-In Complications
Add-PSSnapin is also disallowed. This is immediately a problem for fans of PowerCLI, as it's written as a Snap-In, not a module. The best workaround I've found (though it's kludgy) is to wrap the necessary work in an InlineScript.

Not this:
Add-PSSnapin vmware.vimautomation.core
Get-VM

This:
InlineScript{
    Add-PSSnapin vmware.vimautomation.core
    Get-VM
}

No Implied Parameters
When using workflows, you must explicitly spell out each parameter for every cmdlet you use. This can be a bit fun when learning the name of that parameter you've been taking for granted. The new ISE can be helpful with discovering cmdlet parameters.

Not this:
Get-VM BigGiantVM

This:
Get-VM -Name BigGiantVM

Verbose Workflows
One overlooked feature of workflows is the Activity Common Parameters. These are parameters you pass to individual activities. My favorite so far is -DisplayName. With this parameter, you can label the activities in your workflow so they appear more human friendly, such as "Connecting to remote host AwesomeHost" instead of "Workflow: Line 12, Character 8" while executing. 

Creativity Under Constraints
I've found myself complaining about these details along the way. But actually, they may be forcing me to write better code. By disallowing the easy (and unsustainable) path, I'm reducing what used to be complex scripts/functions into more atomic, modular functions/workflows. This is the beginning of your own personal framework. I say embrace the changes. Besides, it's not like we have much of a choice.

No comments:

Post a Comment