One of my current customers is working on automating their environment as much as possible, and part of that is trying to make standard operations repeatable through tools such as PowerCLI.

Since they are in the process of setting up a reasonably sized environment from scratch and hate clicking the same button over and over again – like most people should – we try to script any operation that takes more than a few minutes to do manually. While it might take a bit more work initially, the code you make is reusable and it allows for great documentation.

So today’s challenge was to tag all the datastores properly for the purpose of storage profiles. Fortunately, all datastores have been given sensible names, so we can use that to our advantage to automate all the work through the power of PowerCLI.

We’ll start with connecting to the vcenter and getting all our datastore clusters. The regex we’ll use later because


connect-viserver vc01
  $regex = [regex] "-[0-9]+"
  $dsclusters = Get-DatastoreCluster -Location REDACTED |? {
    $_.Name -like "*REDACTED*" -or $_.Name -like "*REDACTED*"

Then, we’ll do a foreach loop over the datastore cluster. For each datastore cluster, we’ll split the trailing number from the datastore name. Then, we’ll split the name (which – generally – are named based on functionality, for example: data-read-gold-dc1-nfs or varlog-write-gold-dc2-iscsi) into an array of strings.

We’ll then loop over all the datastores in the current datastore cluster, doublecheck if the tag actually exists, and if it does, assign the tag to the datastore.


$dsclusters |% {
  $name = $regex.Split($_.Name)
  $tags = $name.split("-")
  Get-Datastore -Location $_ |% {
    $curdatastore = $_
    $tags |% {
      if (Get-Tag $_ -errorAction:silentlyContinue) {
        New-TagAssignment -Entity $curdatastore -tag $_ -WhatIf

While this certainly a one-off script, it is relatively easy to adjust to your liking, and can be rewritten to be reusable under any circumstance, as long as your datastore (cluster) naming convention is sane.

Sjors Robroek

Author Sjors Robroek

I have been working in IT from 2000 onwards, starting mainly with Linux then branching out into areas of expertise such as Cisco networking, Microsoft windows and storage. In 2008 I learned more about virtualization and have been specializing in that since. Other skills has certainly not been neglected though and one of my strong points is the knowledge about the related technical areas of virtualization, such as networking and storage. This helps me a lot in getting around in the Software Defined World where automation will be the name of the game.

More posts by Sjors Robroek
26 January 2014