Skip main navigation

PowerShell Workflow

.
17.1
Hello, and welcome back to Worklow runbooks. In the last video, we talked a little bit about runbooks. We created a runbook that actually interacted with Azure resources to switch off machines. We looked at leveraging webhooks to do some more actions, a two-way communication. Something happens to an Azure resource, you want to call the automation on the back of it. When we were looking at the runbook types, there was the Workflow runbook. Now, I think Workflow runbook is quite important and useful for any IT administrator.
48.4
And the reason I say that is because when you create runbooks that are quite long in nature of their execution and something fails midway through the runbook, you don’t need to and want to go through the same process step by step again. You really want to be able to recover from that failure point to execute rest of the stuff. Now, Workflow runbooks allow you to create a checkpoint within your runbook. And the checkpoint preserves the values of all the assets as well as the state of the runbook at that point in time. And then all of the executions thereon are executed based on the values persisted at the point 0’s checkpoint.
86.7
So we’ll do a brief demo of the functionality of Workflow runbooks in which we will set up a checkpoint just to show you how the workflow would work. So let me flip into Azure portal. So we’re within the Azure portal now. As you can see, I’m back into their Runbooks section. I will click on Add a Runbook. And when I click Add a Runbook, I get the option to create a new runbook. I’m going to select the option PowerShell Workflow. Now, let’s call it IaCTraining-WorkflowRb-Demo.
126.4
OK. Click Create.
131.1
Now, behind the scenes, it’s creating a new runbook and just setting up the environment for me to start coding away in my Workflow runbook. Now, while this is happening in the background, I want to show you the script that I’m going to use for the purposes of the demo. Now, really, what I’m doing here is I am using a variable. And I’m setting a value for it. And then I will print the value of that variable before the checkpoint. At this point, I’m going to take a checkpoint, which means all the values of those variables will be persisted. After this point, I’m going to change the value of the variable.
170.6
And I’m going to cause an exception, just force an exception. In this case, I’m doing a 1 plus ABC, which is obviously going to fail. Now, when the script gets suspended, I have the option of resuming the script because I have a checkpoint workflow here. And at this point, the script should only execute from this point onward. So it shouldn’t print before a checkpoint. It should only print after a checkpoint. And it should have the updated value of the variable. Simple enough, right? But it kind of proves the point of the checkpoint workflow-type runbook. So let’s copy this across into our Workflow runbook.
209.1
As you can see here, I am setting an automation variable, which kind of means that I need to have a variable call suspended in place already. And I’ve set the variable up. As you can see, if I click Refresh here, I’ve created a variable called Suspended. And it’s, by default, got a value of True. So if I come here, I’m setting the value to False. So let’s just write the output of that.
240.6
Let’s call it Variable Value.
246.7
Now, this is going to bring– before a checkpoint, this is where we’ll snapshot the values of the variables. At this point, it will print after a checkpoint. At this point, it’s going to get the value of the variable again. So let’s put in another output statement to print the value of the variable. OK. And because the value of the variable will be False, it will go within this condition. And at this point, the value will be updated. The exception would be raised. And the script should just fail. So let’s save this and click on Test Pane. And when I come to the test pane, it gives me the option to start the script.
290.7
Now, as I said earlier as well, when you test these scripts, an isolated environment is provisioned for you, which can take a little bit of time. So in essence, it might take five to seven minutes for the first script execution to complete. But let’s click Start. And as you can see, it’s submitting. It’s queued the job. So we’ll wait for it to spin up the environment and run the execution.
320.4
As you can see, the script execution has completed. And as expected, it’s failed, no surprise. And if we see, the value of False is what we had assigned to the variable. And remember, when I was setting up the variable, I set it up with a value of True. And then it printed before checkpoint, after checkpoint, and then False. So if I go back to the variable now and refresh it, that was the default value that was set up here. And the best thing to do at this point would be to resume the execution of the script.
358.2
Now that the value of the variable is false, next time it executes, it shouldn’t go in the If block and just complete the execution. But the point we’re trying to make here is that the checkpoint has preserved the updated value. And so the onwards execution just takes that from that point onwards. So what we’ll do is click Resume. The execution of the script, we will just start the execution from the checkpoint.
383.8
This would take about five more minutes to complete.
388.6
And you’re probably wondering at this point why, in spite of clicking Resume, nothing’s happening on the screen. It’s just the way the testing screen works. It doesn’t remove the current output. It’s actually, behind the scenes, queued the request. It’s just not started executing yet. So that’s why you see the previous error message. But if I was going to click Resume again, then it would just error out, saying you’ve already resumed a failed task and you can’t re-resume because it’s not completed execution yet. So we’ll just wait three or four minutes for the test environment to just start executing from that point onwards.
428.3
As you can see now on your screen, the status is updated. So it’s saying resuming right at the top here. But the error message from the last failure still stays. So it can be a little bit confusing for certain people. But it’s just the implementation of how it is.
448
Excellent, virtual high five. As you can see, the output continues from after checkpoint. So the before checkpoint doesn’t get reprinted, which kind of proves that the checkpoint state worked. The updated variable value reflects. And the runbook successfully completed. So as you can see here, checkpoint workflow is a good friend of yours, especially if you’re writing long-running runbooks that have a lot of steps in them that re-running would take a lot or would kind of expect a certain state which, if changed, could cause issues in your runbooks. Or so use checkpoints. They’re really useful.

In the previous activities, you learned about runbooks, types of runbooks and how to create a runbook that interacts with Azure resources to switch off machines. You also discovered how to leverage webhooks to perform two-way communication.

When we looked at runbook types, you were introduced to the workflow runbook. The workflow runbook is an important and useful tool for any IT administrator. In this step, we’ll explore workflow runbooks and learn how to create checkpoints that allow you to recover your runbook at its failure point.

What is PowerShell Workflow?

A Windows PowerShell workflow is a sequence of programmed, connected steps that perform long-running tasks or require the coordination of multiple steps across multiple devices or managed nodes. Workflows let IT pros and developers author sequences of multidevice management activities, or single tasks within a workflow, as workflows.

By design, workflows can be long-running, repeatable, frequent, parallelisable, interruptible, stoppable, and restartable. They can be suspended and resumed and can also continue after an unexpected interruption, such as a network outage or computer restart.

The benefits of using workflows include:

  • Windows PowerShell scripting syntax. Workflows extend PowerShell, which makes it is easy for IT professionals who are already familiar with scripting.

  • Multidevice management. You can simultaneously apply workflow tasks to hundreds of managed nodes. Workflows automatically add common parameters to enable multidevice management scenarios.

  • Running a single task to manage complex end-to-end processes. You can combine related scripts or commands that act on an entire scenario into a single workflow. Status and progress of activities within the workflow are visible at any time.

  • Automated failure recovery. Workflows survive both planned and unplanned interruptions, such as computer restarts. You can suspend workflow operation, then restart or resume the workflow from the point at which it was suspended. You can author checkpoints as part of your workflow so that you can resume the workflow from the last persisted task (or checkpoint), instead of restarting the workflow from the beginning.

  • Connection and activity retries. By using workflow common parameters, workflow users can retry connections to managed nodes if network-connection failures occur. Workflow authors can also specify activities that must run again if the activity cannot be completed on one or more managed nodes (for example, if a target computer was offline while the activity was running).

  • Connect and disconnect. Users can connect and disconnect from the computer that’s running the workflow, but the workflow remains running. For example, if you are running and managing the workflow on two different computers, you can log off or restart the computer from which you are managing the workflow. This enables you to monitor workflow operations from another computer (such as a home computer) without interrupting the workflow.

  • Task scheduling. Workflow tasks can be scheduled and then started when specific conditions are met, as with any other Windows PowerShell cmdlet or script.

Workflow Syntax

To write the workflow, you can use a script editor such as the Windows PowerShell Integrated Scripting Environment (ISE), which enforces workflow syntax and highlights syntax errors. A benefit of using this tool is that it automatically compiles your code and allows you to save the artefact. The syntactic differences between scripts and workflows are significant, so a tool that knows workflows, as well as scripts, will save you significant coding and testing time.

Steps for creating the Workflow Syntax:

  1. Begin with the workflow keyword, which identifies a workflow command to Windows PowerShell. The workflow keyword is required in a script workflow.
  2. The name of the workflow follows the workflow keyword.
  3. The body of the workflow is enclosed in braces. A workflow is a Windows PowerShell command type. Select a name with a verb-noun format.
**workflow Test-Workflow**

**{**

**...**

**}**

To add parameters to a workflow, use the **Param** keyword. These are the same techniques that you use to add parameters to a function. Lastly, simply add your standard PowerShell commands.

**workflow MyFirstRunbook-Workflow**

**{**

**Param(**

**[string]$VMName,**

**[string]$ResourceGroupName**

**)**

**....**

**Start-AzureRmVM -Name $VMName -ResourceGroupName $ResourceGroupName**

**}**

Checkpoint and Parallel Processing

Workflows let you implement complex logic within your code. Two unique features of workflows are checkpoints and parallel processing.

Checkpoints

A checkpoint is a snapshot of the current state of the workflow that includes the current value for variables and any output generated to that point. If a workflow ends in error or is suspended, the next time it’s run it will start from its last checkpoint instead of the start of the workflow.

You can set a checkpoint in a workflow with the Checkpoint-Workflow activity. For example, in the following sample code, if an exception occurs after Activity2, the workflow will end. When the workflow is run again, it starts with Activity2 because this followed just after the last checkpoint set.

<Activity1>

Checkpoint-Workflow

<Activity2>

<Exception>

<Activity3>

Parallel Processing

A Parallel script block has multiple commands that run concurrently instead of sequentially, as occurs with a typical script.

In the following example, two VMs will be started concurrently:

Parallel

{

Start-AzureRmVM -Name $vm0 -ResourceGroupName $rg
Start-AzureRmVM -Name $vm1 -ResourceGroupName $rg

}
This article is from the free online

Microsoft Future Ready: DevOps Development, Implementation and Azure Automation

Created by
FutureLearn - Learning For Life

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education