Working with vSphere folders
In a VMware vSphere environment, you can use folders to organize your infrastructure. In the vSphere web client, you can create folders in the Hosts and Clusters
, VMs and Templates
, Storage
, and Networking
inventories. The following screenshot shows an example of folders in the VMs and Templates
inventory.
You can browse through these folders using the vSphere PowerCLI Inventory Provider. PowerCLI also has a set of cmdlets to work with these folders: Get-Folder
, Move-Folder
, New-Folder
, Remove-Folder
, and Set-Folder
.
You can use the Get-Folder
cmdlet to get a list of all of your folders:
PowerCLI C:\> Get-Folder
Or you can select specific folders by name using the following command line:
PowerCLI C:\> Get-Folder –Name "Accounting"
All folders are organized in a tree structure under the root folder. You can retrieve the root folder with:
PowerCLI C:\> Get-Folder -NoRecursion Name Type ---- ---- Datacenters Datacenter
The root folder is always called Datacenters
. In this folder, you can only create subfolders or datacenters.
Folders in vSphere are of a certain type. Valid folder types are VM
, HostAndCluster
, Datastore
, Network
, and Datacenter
. You can use this to specify the type of folders you want to retrieve. For example, to retrieve only folders of type VM, use:
PowerCLI C:\> Get-Folder -Type VM
A problem with folders is that you don't get the full path from the root if you retrieve a folder. Using the New-VIProperty
cmdlet, you can easily add a Path
property to a PowerCLI Folder
object:
PowerCLI C:\> New-VIProperty -Name Path -ObjectType Folder -Value { # $FolderView contains the view of the current folder object $FolderView = $Args[0].Extensiondata # $Server is the name of the vCenter server $Server = $Args[0].Uid.Split(":")[0].Split("@")[1] # We build the path from the right to the left # Start with the folder name $Path = $FolderView.Name # While we are not at the root folder while ($FolderView.Parent){ # Get the parent folder $FolderView = Get-View -Id $FolderView.Parent -Server $Server # Extend the path with the name of the parent folder $Path = $FolderView.Name + "\" + $Path } # Return the path $Path } -Force # Create the property even if a property with this name exists
In this example, you see that the #
character in PowerShell is used to comment.
Using the new Path property, you can now get the path for all of the folders with:
PowerCLI C:\> Get-Folder | Select-Object -Property Name,Path
You can use the Path
property to find a folder by its complete path. For example:
PowerCLI C:\> Get-Folder | >> Where-Object {$_.Path -eq 'Datacenters\Dallas\vm\Templates'} >>