Skip to content

50. PowerShell Workflows

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

PowerShell Workflow is a feature that was introduced starting with PowerShell version 3.0. Workflow definitions look very similar to PowerShell function definitions, however they execute within the Windows Workflow Foundation environment, instead of directly in the PowerShell engine.

Several unique "out of box" features are included with the Workflow engine, most notably, job persistence.

50.1: Workflow with Input Parameters

Just like PowerShell functions, workflows can accept input parameter. Input parameters can optionally be bound to a specific data type, such as a string, integer, etc. Use the standard param keyword to define a block of input parameters, directly after the workflow declaration.

1
2
3
4
5
6
7
8
workflow DoSomeWork {
  param (
    [string[]] $ComputerName
  )
  Get-Process -ComputerName $ComputerName
}

DoSomeWork -ComputerName server01, server02, server03

50.2: Simple Workflow Example

1
2
3
workflow DoSomeWork {
  Get-Process -Name notepad | Stop-Process
}

This is a basic example of a PowerShell Workflow definition.

50.3: Run Workflow as a Background Job

PowerShell Workflows are inherently equipped with the ability to run as a background job. To call a workflow as a PowerShell background job, use the -AsJob parameter when invoking the workflow.

1
2
3
4
5
6
7
workflow DoSomeWork {
  Get-Process -ComputerName server01
  Get-Process -ComputerName server02
  Get-Process -ComputerName server03
}

DoSomeWork -AsJob

50.4: Add a Parallel Block to a Workflow

1
2
3
4
5
6
7
workflow DoSomeWork {
  parallel {
    Get-Process -ComputerName server01
    Get-Process -ComputerName server02
    Get-Process -ComputerName server03
  }
}

One of the unique features of PowerShell Workflow is the ability to define a block of activities as parallel. To use this feature, use the parallel keyword inside your Workflow.

Calling workflow activities in parallel may help to improve performance of your workflow.