PowerCLI to Select Arbitrary Host Ranges via Regex

This is another quickie (I've had a very PowerCLI rich couple of months!).  We've been doing a lot of mass ESXi host manipulations lately and typically grab the hosts in batches of 8.  As such, I've needed to be able to target a specific set of 8 ESXi servers with some of my PowerCLI commands.  The first 8 (named esx01-esx08) are really easy to grab with string matching:

get-vmhost *esx0[1-8]*

That command will return all ESXi hosts in that range.  That same trick doesn't work so well with other batches of ESXi hosts (until you get into the esx41-48 range), as the square brackets represent only a single character.  That means that get-vmhost *esx[09-16]* is not a valid construct.  Fortunately, this is a pretty easy match to make with a regular expression: esx(09|1[0-6])

That regex works because of a few important symbols.  The | is the key to it; it means "or".  A simple example would be "09|10" which matches anything with "09" or "10" in it.  The "1[0-6]" will match a "1" immediately followed by the numbers 0-6 and so matches 10-16.  Combined (09|1[0-6]), they match 09 or anything in the range of 10-16.  In this case, I want to make sure that I'm only matching esx09-esx16 though, and so I need to include the "esx" preface.  I put the numeric suffix in parenthesis in order to contain the "or" logic.  "esx(09|1[0-6])" is logically equivalent to "esx09|esx1[0-6]", but it saves a character (or more if your prefix is longer than 3 characters).

The only drawback is that the get-vmhost cmdlet doesn't understand regular expressions.  Fortunately, the "where-object" cmdlet does (which is aliased by a ?), when as you use the -match operator in its expression:

get-vmhost | ? {$_.name -match "esx(09|1[0-6])"}
get-vmhost | ? {$_.name -match "esx(1[7-9]|2[0-4])"}
etc.

Comments

Popular posts from this blog

Orphaned VMDK Files

Migrating from one vCenter to Another, Improved

Deleting Orphaned (AKA Zombie) VMDK Files