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.

Related articles

  • Application Modernization
  • Digital Workspace
  • Cloud Infrastructure
  • ITTS (IT Transformation Services)
  • Managed Security Operations
  • Multi-Cloud Platform
  • Backup & Disaster Recovery
Visit our knowledge hub
Visit our knowledge hub
ITQ

Let's talk!

Knowledge is key for our existence. This knowledge we use for disruptive innovation and changing organizations. Are you ready for change?

"*" indicates required fields

Your first name*
Your last name*