PowerCLIVMware

PowerCLI to change the Discovered virtual machine folder name

Are you bothered by the name of the default “Discovered virtual machine” folder in VMs and Templates? If there is more than one VM in the Folder shouldn’t it be “Discovered virtual machines”? But… what if there is only one VM in the folder then “Discovered virtual machines” would be wrong, crap.

Saw this tweet from @jasonboche earlier (Follow him, cause he is pretty awesome).
jasontweet
Apparently this is a real world problem 🙂

So just messing around (because it is better than work on a Friday afternoon before a holiday weekend) I put together a little PowerCLI to help out.


$VMFolder = Get-Folder | where {$_.name -match "Discovered virtual machine"}
$totalVMsinDefaultFolder = Get-Folder | where {$_.name -match "Discovered virtual machine"} | Get-VM
$Grammar = "is"
$Plural = ""

if ($totalVMsinDefaultFolder.count -gt 1 -or $totalVMsinDefaultFolder.count -eq 0)
{
  $Grammar = "are"
  $Plural = "s"
}

Write-Host "There $Grammar"  $totalVMsinDefaultFolder.Count  " VM$Plural in the folder which is currently named"  $VMFolder.Name

if ($totalVMsinDefaultFolder.count -gt 1 -and $VMFolder.Name -ne "Discovered virtual machines") 
{
    Get-Folder | where {$_.name -match "Discovered virtual machine"} | Set-Folder -Name "Discovered virtual machines"
}

if ($totalVMsinDefaultFolder.count -le 1 -and $VMFolder.Name -ne "Discovered virtual machine") 
{
    Get-Folder | where {$_.name -match "Discovered virtual machine"} | Set-Folder -Name "Discovered virtual machine"
}

Basically the script gets the current folder containing the name “Discovered virtual machine” and then gets the VMs in the folder (It will not work if you have two folders with names containing “Discovered virtual machine” or if there is no folder name containing “Discovered virtual machine”).

The $totalVMsinDefaultFolder.Count is the number of VMs in the folder. It then, based on the VM count, prints out what it found and sets the name of the folder to either “Discovered virtual machines” if there is more than 1 VM in the folder or to “Discovered virtual machine” if there is 1 or less in the folder. If the folder name is already set correctly it does, well, nothing.

I may take it a step further and if there are no VMs in the Folder rename it to “No Discovered virtual machines” but probably not.

Of course there is probably a better or simpler way to do this, but this is like 2 1/2 minutes worth of work. Not well tested so… beware if you use it against a production environment (but it shouldn’t hurt anything – I hope).

Like I said… better than doing real work.

Leave a Reply

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

5 − one =