VMware Cloud Community
usov_is
Contributor
Contributor

move vm to subfilders

Hi.

I use vsphere web client 6.7
There is a list of VMs. There are two entries in the annotation of each VM. 
 
in inventory I have folders with the name from the first entry in annatation and subfolders from the second entry in annatation.
help with writing a script to move VMs to subfolders according to annotation 
Reply
0 Kudos
9 Replies
LucD
Leadership
Leadership

What is the layout of these fields in the Annotation?
How can a script find the 1st and 2nd entry?


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
usov_is
Contributor
Contributor

<#$vms = Get-VM

foreach ($vm in $vms) {

$Critical = $vm.CustomFields.Item("Critical level")
$id = $vm.CustomFields.Item("Service ID")

#get-folder -Name $Critical  
new-folder -Name $id -Location (Get-Folder $Critical)

Move-Inventory -Item $vm -Destination $id
}

#>

Reply
0 Kudos
usov_is
Contributor
Contributor

or

<#

$vms = Get-VM

foreach ($vm in $vms) {

$Critical = $vm.CustomFields.Item("Critical level")
$id = $vm.CustomFields.Item("Service ID")

get-folder -Name $Critical | new-folder -Name $id

move-vm -VM $vm -Destination $id
}

#>

Reply
0 Kudos
LucD
Leadership
Leadership

You could try something like this.
If a folder doesn't exist, the script will create it.

foreach ($vm in Get-VM) {

    $Critical = $vm.CustomFields.Item("Critical level")

    $id = $vm.CustomFields.Item("Service ID")

    try{

        $cFolder = Get-Folder -Name $Critical -Type VM -ErrorAction Stop

    }

    catch{

        $cFolder = New-Folder -Name $Critical -Location (Get-Folder -Name vm) -Confirm:$false

    }

    try{

        $iFolder = Get-Folder -Name $id -Type VM -Location $cFolder -ErrorAction Stop

    }

    catch{

        $iFolder = New-Folder -Name $id -InventoryLocation $cFolder -Confirm:$false

    }

    Move-VM -VM $vm -Destination $id -Confirm:$false

}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
usov_is
Contributor
Contributor

can we specify the full path to the subfolder in the variable and use it when moving?

# Move-VM -VM $vm -Destination 'full path to subfolder' -Confirm:$false

Reply
0 Kudos
LucD
Leadership
Leadership

Correction, that should be InventoryLocation instead of Destination.

And no, you have to specify a folder, you can't use the full path


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
usov_is
Contributor
Contributor

Tried to use Inventory Location. does not find given instead. In which version of powercli is it present

# Move-VM -VM $vm -InventoryLocation 'subfolder' -Confirm:$false

Reply
0 Kudos
LucD
Leadership
Leadership

It was added in PowerCLI 6.5.2, see VMware PowerCLI Change Log


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Reply
0 Kudos
usov_is
Contributor
Contributor

thanks, the script is working
Reply
0 Kudos