Bagikan melalui


Scaling out PowerShell with PowerShell Direct

I have spent a bunch of time this week working on various demos for Ignite in Atlanta.  While building these demos I have been heavily using PowerShell Direct to orchestrate large sets of virtual machines.

A common pattern that I encounter is that I will write one piece of code – and then want to run it inside half a dozen virtual machines.  Today I am taking a moment to share some tips and tricks I have picked up.

Variables

I usually start my scripts with a variable block that stores things like file paths, domain names, etc…  When I use PowerShell Direct – I need to get the variables I need into the remote PowerShell session on the virtual machine.  A typical approach to this would be to use arguments and parameters (the first code sample below).  However, this can quickly get unruly when you need to pass through a large number of variables.  A better option is to use $Using (the second code sample below):

With this approach you just put $Using: in front of the variable that you want to reference from the parent scope – and you have access.  This makes for cleaner code – and it also makes it easier when you realize that you need access to “yet another variable” that you had not passed through as a parameter.

Functions

This is a really neat trick.  Personally, if I have written the same chunk of code three times in a single script – I will make it a function.  But what to do when I then want to take a set of functions and run it on multiple virtual machines?  Well, this:

What I am doing here is:

  1. Defining three functions (empty ones in this case – it is just a sample)
  2. Creating a function definition template
  3. Loading it in my remote PowerShell session

I can then use these functions on the virtual machine directly.  The best thing is that if I then connect to another virtual machine, one line will get me access to all of my functions.  Yay!

Cheers,
Ben

Comments

  • Anonymous
    September 27, 2016
    FnRemoting in PowerShell. Way to go!
  • Anonymous
    October 19, 2016
    Thanks Ben,That are really need tips. Carsten