Get vSphere Tags out of a category with PowerCLI

Introduction to vSphere Tags

Using vSphere tags in your VMware environment is no longer a secret. It gives you flexibility, easier management and control of your virtual machines.

If you want to see how to use vSphere Tags with Veeam check out my article here: Using VM Tags with vSphere and Veeam Backup & Replication

When it comes to backup virtual machines via vSphere Tags you will most likely force the strategy to give every single virtual machine a tag.

There is the famous “no backup” tag for virtual machines which are excluded from backup. Furthermore, all the other vSphere tags are necessary to declare your SLA policies.

To ensure that your tagging strategy is resilient, you will need to tag every single virtual machine in your environment. But what if your environment is in undergoing change and virtual machines are deployed and deleted heavily. You will moste likely have any kind of monitoring in place such as VeeamONE to monitor if all your virtual machines have a vSphere tag in place.

Today I want to show you a way on how to achieve this kind of monitoring with a simple PowerCLI script.

What does this script do with your vSphere Tags?

The script does the following:

  • It connects to your vCenter Server
  • It checks all virtual machines if they have a vSphere Tag out a category you decide
  • When it finds virtual machines with no tags out of the desired category it writes an output
  • The outputs gets send via E-Mail to an email address you provide
  • It checks the output path for old files and deletes them if they are older than X days

My recommendation is to setup a scheduled task which runs once or twice a day to check your environment.

The script:

Please keep in mind, that I will maintain this script on github not in this blog post: Here is the link to the script on github

<#
.SYNOPSIS
    Get_VMs_Without_Tags.ps1 - PowerShell Script to gather all VM's from your vCenter server who don't have a vSphere Tag.
.DESCRIPTION
    This script is used to gather all VMs from your vCenter server who don't have a tag out of a specific category.
    The output is saved into a file on the destination you decide.
    The file output ONLY gets send via E-Mail if the amount of VMs without a tag is greater than 0, which means you will only get a mail if a VM exists without a vSphere Tag !
.OUTPUTS
    Results are printed to the console.
.NOTES
    Author        Falko Banaszak, https://virtualhome.blog, Twitter: @Falko_Banaszak
    
    Change Log    V1.00, 27/05/2020 - Initial version: Gathers all VMs without a vSphere Tag and places the output into a file.
    Change Log    V1.01, 28/06/2020 - Update: added function to send E-Mails if the file has contents
    Change Log    V1.02, 28/06/2020 - Update: added function to delete finding files older than 30 days
    Change Log    V1.03, 04/06/2020 - Update: added the VMware credential store item to make the connection to vCenter
.LICENSE
    MIT License
    Copyright (c) 2019 Falko Banaszak
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
#>

# Path to the file which gets send as an attachement
# Adjust the variable $WorkingPath to your needs !
$FileToAttach = "$WorkingPath\VMsWithoutTags_$(Get-Date -format dd_MM_yyyy_hh_mm_ss).txt"
$WorkingPath = "C:\VMsWithoutTags\"

# E-Mail settings
# Adjust all these mail variables to your needs except the $Attachement variable !
$From = "veeam-server@domain.com"
$To = "veeam-administrator@domain.com"
$Attachment = "$FileToAttach"
$Subject = "VMs without Tags"
$Body = "Please find attached the list of VMs which are not tagged"
$SMTPServer = "smtp-server.domain.com"
$SMTPPort = "25"

# VMware settings
# Adjust the VMware credentials and variables to your needs. Also don't forget to use a path where the credential.xml will be saved.
$vCenterServer = "vcenter.domain.com"
$vCenterUser = "domain\vcenteruser"
$vCenterUserPassword = 'y0ur_53cur3_p455w0rd'
$CredentialXML = "C:\Path\credentials.xml"
New-VICredentialStoreItem -Host $vCenterServer -User $vCenterUser -Password $vCenterUserPassword -file $CredentialXML
$Credentials = Get-VICredentialStoreItem -File $CredentialXML

# Enter your tag category you want to check here
$TagCategory ="Veeam Backup Tags"

# Load the PowerCLI SnapIn and set the configuration
Add-PSSnapin VMware.VimAutomation.Core -ea "SilentlyContinue"
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false | Out-Null

# Connect to the vCenter Server with collected credentials
Connect-VIServer -Server $Credentials.Host -User $Credentials.User -Password $Credentials.Password | Out-Null

# Get all VMs and check if they have a vSphere Tag out of the given category
Get-VM | Where-Object {(Get-TagAssignment $_ -Category $TagCategory) -eq $null} | Out-File -FilePath $FileToAttach

# Finally check if the file contains content, which means there is a VM without a tag and send it via e-mail
if ($null -eq (Get-Content -Path "$FileToAttach")) {
    Write-Host "No VMs found with a missing vSphere Tag" -ForegroundColor Green
}
else {
    Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -Attachments $Attachment -Priority High -DeliveryNotificationOption None -SmtpServer $SMTPServer -Port $SMTPPort
}
# Disconnecting from the vCenter Server
Disconnect-VIServer * -Confirm:$false
Write-Host "Disconnected from your vCenter Server $vCenterServer" -ForegroundColor Green

# Check if written files are older than 30 days and delete them
$DaysToDelete = "-30"
$CurrentDate = Get-Date
$DeleteDays = $CurrentDate.AddDays($DaysToDelete)
Get-ChildItem $WorkingPath | Where-Object { $_.LastWriteTime -lt $DeleteDays } | Remove-Item

How to set it up for your environment

Basically, you simply need to add all the relevant information in the variables which I framed in red in the below screenshot.

vSphere Tags VMware

  • the path where you want to save the outputs
  • the e-mail settings
  • your vSphere credentials and connection
  • your desired tag category

As always, thanks for reading and have a nice day !

If you encounter errors or if you want to share feedback, don’t hesitate to do here with a comment or on github !

About Falko Banaszak

Falko is a consultant based in Germany working for SVA GmbH. He has a strong focus on virtualization, data backup, disaster recovery infrastructures and a passion for Microsoft 365 & storage systems. He´s a VMware vExpert & Veeam user group leader in Germany. VCP-DCV, VMCE, VMCA.

Check Also

Veeam Backup for Office 365

Measure-VBOOrganizationFullBackupSize: The operation has timed out

Introduction Sometimes timeouts can happen during the measurement of an O365 organization by using the …

Leave a Reply

Your email address will not be published. Required fields are marked *