Not sure if I understood your point 2) but here are 2 scripts that should do what I think you want to do.
Export the VMs and the folderstructure.
New-VIProperty -Name 'BlueFolderPath' -ObjectType 'VirtualMachine' -Value {
param($vm)
function Get-ParentName{
param($object)
if($object.Folder){
$blue = Get-ParentName $object.Folder
$name = $object.Folder.Name
}
elseif($object.Parent -and $object.Parent.GetType().Name -like "Folder*"){
$blue = Get-ParentName $object.Parent
$name = $object.Parent.Name
}
elseif($object.ParentFolder){
$blue = Get-ParentName $object.ParentFolder
$name = $object.ParentFolder.Name
}
if("vm","Datacenters" -notcontains $name){
$blue + "/" + $name
}
else{
$blue
}
}
(Get-ParentName $vm).Remove(0,1)
} -Force | Out-Null
$dcName = "MyDC"
Get-VM -Location (Get-Datacenter -Name $dcName) |
Select Name,BlueFolderPath |
Export-Csv "C:\vm-folder.csv" -NoTypeInformation -UseCulture
The script uses a New-VIProperty to fetch the blue folderpath for a VM.
Import the folder structure and move existing VMs.
$newDatacenter = "MyNewDC"
$newFolder = "Folder1"
$startFolder = New-Folder -Name $newFolder -Location (Get-Folder -Name vm -Location (Get-Datacenter -Name $newDatacenter))
Import-Csv "C:\vm-folder.csv" -UseCulture | %{
$location = $startFolder
$_.BlueFolderPath.TrimStart('/').Split('/') | %{
$tgtFolder = Get-Folder -Name $_ -Location $location -ErrorAction SilentlyContinue
if(!$tgtFolder){
$location = New-Folder -Name $_ -Location $location
}
else{
$location = $tgtFolder
}
}
$vm = Get-VM -Name $_.Name -ErrorAction SilentlyContinue
if($vm){
Move-VM -VM $vm -Destination $location -Confirm:$false
}
}
The complete folder structure that was exported will now be imported in datacenter MyNewDC under the folder Folder1.