VMware Cloud Community
pelleasdaphnis
Contributor
Contributor

Get templates by vSphere tag name

What's the shortest, most direct call to get a list of templates by a given vSphere tag applied to them? With VMs it's easy with "Get-VM -Tag <my_tag>", but there's not a similar way with templates.

0 Kudos
4 Replies
DZ1
Hot Shot
Hot Shot

You could pull them if they are in the same tag category.  Get-TagAssignment -Category 'Your category'.  Assuming all the templates are in the 'Your category' category, you would pull all of them. 

0 Kudos
pelleasdaphnis
Contributor
Contributor

There would be multiple tags in this category, plus running this cmdlet returns objects only.

0 Kudos
ccalvetTCC
Enthusiast
Enthusiast

Hi,


There is no direct call.

TAG in the web client are not available in the standard API.

In others words the PowerCLI team has done a great job with get-vm and the parameter “TAG” which is very convenient.

Solution:
Create a feature request and ask the PowerCLI team to add “TAG” as a parameter to the get-template cmdlet.

Workaround:

I have created this function as a dirty workaround.

function Get-TemplateWithTag{

param(

$TagNameArray

)

    process{

    $AllTemplatesAndTag = get-template | foreach {($MyTemplate = $_)} | get-tagassignment | select-object @{name="Template";Expression={$MyTemplate}}, @{name="TagName";Expression={$_.tag.Name}},@{name="TagCategory";Expression={$_.tag.Category}}

    $AllTemplateWithDuplicate = $AllTemplatesAndTag | foreach-object{

            if ($TagNameArray -contains $_.TagName){

            $_.Template

            }

        }

   

    $AllTemplateWithoutDuplicate = $AllTemplateWithDuplicate | get-unique

    $AllTemplateWithoutDuplicate

    }

}

$TagNameArray = "VM Level","Datacenter01"

Get-TemplateWithTag -TagNameArray $TagNameArray

The output will be one or many Template objects. Only one template will be reported even if one template is associated to multiples tag name in the $TagNameArray

I am not using TAG object as a parameter.
It should be possible but in that case it will be necessary to check against TagName and TagCategory.

It is a workaround so i keep it simple.

Known limitation, it will not work well with a tag with an identical name in two separate category.

In my testlab i have the following tags:

Category Name

Location Datacenter01

Backup VM level

Blog: http://thecrazyconsultant.com/ | Twitter: @ccalvetTCC
0 Kudos
pelleasdaphnis
Contributor
Contributor

That's great, thanks for your efforts, TheCrazyConsultant! I have put in a request with Alan and the PowerCLI powers that be, and I will be looking at your function more closely over the weekend.

0 Kudos