Script: How to get VM with Tag Assignment and export results to csv using PowerCLI or Powershell

This is a quick blog post on retrieving VM tag data from vcenter and exporting result to csv

## VMs with Tags and Used Disk Space
Get-VM | Get-TagAssignment |
   where {$_.Tag -like 'tag-1*'} |
  Select @{N = 'VM'; E = {$_.Entity.Name}}, @{N = 'UsedSpace'; E = {$_.Entity.UsedSpaceGB}} |
   Export-CSV C:\temp\vms-tag.csv -NoTypeInformation

## Below works aswell 

Get-VM | Get-TagAssignment |
where{$_.Tag -like 'tag-1*'} |
Select @{N='VM';E={$_.Entity.Name}} |
Export-CSV C:\temp\vms-tag-1.csv -NoTypeInformation

## VMs with no tag 

$VMsWithNoTag = Get-VM | ?{(Get-TagAssignment $_) -eq $null}


## Bonus short script
## Get VM Snapshot Information for all Snapshots and send that information to
C:\temp\AllSnapshots.txt

Write-Output "VMWare Snapshot Report for $(get-date -f MM-dd-yyyy)" | Out-File $Log -Append

$output = @()
foreach ($vm in Get-VM) {
   $tags = ((Get-TagAssignment -Entity $vm | select -ExpandProperty Tag).Name -join ", ")
   foreach ($snapshot in $vm | Get-Snapshot | Where-Object { $_.Created -lt (Get-Date).AddDays(-3) }) {
       $obj = [PSCustomObject]@{VM = $vm.Name; Name = $snapshot.Name; Created = $snapshot.Created; SizeGB = $snapshot.SizeGB; Tags = $tags}
       $output += $obj
   }
}
$output | Format-List | Out-File $Log -Append

You May Also Like

About the Author: VirtuallyThatGuy

1 Comment

  1. Do you have a script to import them into new vCenter? Basically I want to use your export script and then on the new vCenter, import the tags on the VMs once the hosts and VMs have been moved over.

Leave a Reply

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