Hello,
I’m just starting my learning journey in scripting at Powercli and I’m currently writing one to move VMs from anywhere at the Datacenter level to a specific folder inside the same Datacenter that matches the “Value” of a specific custom attribute, at the VM. The idea is to run this script once and a while to sort the VMs at the correct folder based on the VM Custom Attributes field.
I have many Datacenter inside the same vCenter and each Datacenter has the same structure of folders (i.g. production, development, infrastructure ) The idea is to move the VM for the specific folder set the Custom Attribute and if the “Value” is empty or does not match whit any folder name it should move the VM to the “Discovered virtual machines” folder. I have tried some functions from LucD and It gave some good ideas, but I could not implement it well.
When I run the script for singles machines it seems to work, but when the CSV file has a more than one VM of fields it behavior unexpectedly. I’m sure my script is full of mistakes, but I’m trying.
get-vm | get-annotation -customattribute "VM Folder" | Select-Object annotatedentity, value | Export-Csv -Path C:UsersmhopsDocumentsmovevmsattributes.csv –NoTypeInformation Import-Csv C:UsersmhopsDocumentsmovevmsattributes.csv -UseCulture | %{ $vm = Get-VM -Name $_.AnnotatedEntity | Select-Object Name $folder = Get-Folder -Name $_.Value $dc = Get-View -ViewType VirtualMachine -filter @{ "name" = $vm.Name} | Select-Object -Property Name, @{ Label = "Datacenter"; Expression = { (Get-view (Get-View (Get-view $_.parent).parent).Parent).name } } | Select-Object Datacenter $path = Get-Datacenter -Name $dc.Datacenter | Get-Folder -Name $folder $pathdefault = Get-Datacenter -Name $dc.Datacenter | Get-Folder -Name "Discovered virtual machine" if (!$folder.Value) { Move-VM -VM $vm.Name -InventoryLocation $pathdefault } else { Move-VM -VM $vm.Name -InventoryLocation $path } }
Thanks for your help