Export a list of VMs without a specific tag with PowerCLI

I'm trying to export a CSV file that has a list of all VM's in a cluster that don't have a specific tag that I'm using for rightsizing. However, the CSV isn't populating with anything other than this: ÿþ

Get-Module -Name VMware* -ListAvailable | Import-Module -Force
$exportto = "C:\Users\username\Desktop\rightSizingFilter3.csv"
$VMs = Get-Cluster -name clustername | Get-VM
 
foreach ($VM in $VMs){
    If (((Get-Tagassignment $VM).Tag.Name -notcontains "testtag")){
         Out-file $exportto -Append
    }
}

Solution 1:

If you want a CSV, you may get more consistent results by changing Out-File ... to be:

Export-Csv -InputObject $VM -Path $ExportTo -Append -NoTypeInformation

I believe the output of Get-VM is a JSON object, so outputting as a file may be causing the format to not be what you're looking for. Even with Export-Csv, you may still find that some of the data isn't readily converted to CSV format, so you can clean up the output even more by selecting just the tags or attributes that you want and then exporting that all to CSV.

Here's the code that I tested:

Get-Module -Name VMware* -ListAvailable | Import-Module -Force
Connect-ViServer -Server [SERVERNAME] -Credential (Get-Credential)
$ExportTo = ".\rightSizingFilter3.csv"
$VMs = Get-Cluster -Name [CLUSTERNAME] | Get-VM
 
foreach ($VM in $VMs) {
    If ( ((Get-Tagassignment $VM).Tag.Name -notcontains "testtag") ) {

         Export-Csv -InputObject $VM -Path $ExportTo -Append -NoTypeInformation
    }
}

Solution 2:

I also got it to work from the snippet below:

$RS = foreach ($VM in $VMs){
    If (((Get-Tagassignment $VM).Tag.Name -notcontains "testtag")){
        Write-Output $VM
    }
}
$RS | Out-file $exportto -Append