Creating VMs and Templates folders with PowerCLI

As part of a migration from one vCenter to another, I wanted to recreate the same VMs and Templates look which meant recreating the folders. This is VERY slow in the vSphere Web Client and only slightly less tedious in the C# client, so I thought I’d use PowerCLI to do the trick. Here is the folder structure I wished to recreate:

Location
-Development
-Pending DeComm
-Production
  -Active Directory Domain Controllers
  -Linux Servers
  -RDP Servers
-Templates
  -Template VMs

PowerCLI has a cmdlet called New-Folder. Unfortunately, it only creates folders of the Hosts and Clusters type. To create a new VMs and Templates folder, we have to use the Get-View cmdlet. By viewing a datacenter or folder and filtering on the proper location, we can call methods to create a folder with the right context:

Continue reading

PowerCLI One-Liner – Mark all VM optical drives as Client

I’ve seen a number of articles offering PowerCLI one-liners to find all VMs with connected optical drives, or set to use a datastore, or a number of other possibilities, and mark the drives as disconnected. This is helpful, but may still cause a problem with vMotions if the optical drive is pointing to a non-shared datastore ISO. vMotion does not care if the optical drive is connected, but it does care that it’s pointing to a datastore that not all hosts can see. This one-liner will find all VMs with an ISOPath set for the optical drive and reset it to Client.

Get-VM | Get-CDDrive | Where {$_.ISOPath -ne $null} | Set-CDDrive -NoMedia -Confirm:$false

This looks for all CDDrive objects where the ISOPath value is not null and calls Set-CDDrive with the flag -NoMedia. This should take care of all the VMs where someone has set it to use an ISO on the datastore. It will NOT fix the mapping for VMs connected to the Host Device or Client Device – however, those are more rare and do not usually stand between you and a vMotion. On those rare instances, you may still need to manually dismount the optical drive on the VM or use a PowerCLI one-liner targeting those settings.