Skip to content

Instantly share code, notes, and snippets.

@jcppkkk
Last active March 29, 2023 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcppkkk/0e54ed7a879b29fefce4da691d4a1b9b to your computer and use it in GitHub Desktop.
Save jcppkkk/0e54ed7a879b29fefce4da691d4a1b9b to your computer and use it in GitHub Desktop.
Migrate folder structure from old to new vSphere vCenter
Import-Module VMware.PowerCLI
$global:DefaultVIServers | Disconnect-VIServer -Confirm:$false
$srcVc = "SRC-VCENTER-FQDN"
$dstVc = "DST-VCENTER-FQDN"
Connect-VIServer $srcVc -User xxx -Password xxxxxx
Connect-VIServer $dstVc -User xxx -Password xxxxxx
$sourceDatacenterName = "SRC-DS-NAME"
$targetDatacenterName = "DST-DS-NAME"
$moveVms = $true # Should VMs in target vCenter be moved to folders by Name best effort
# Creates the folder and moves the VMs
Function Create-Folder($f, $t, $targetRoot) {
$from_name = $f.name -replace "\[", "``["
Write-Host "== Create-Folder" $t.name "/" $from_name
try {
$targetFolder = New-Folder -Name $f.name -Location $t -ErrorAction Stop
}
catch {
$targetFolder = Get-Folder -Name $from_name -Location $t -NoRecursion -ErrorAction Stop
}
if ($targetFolder -eq $null) {
throw "Error creating folder" + $t.name + "/" + $f.name
}
if ($moveVms) {
#Write-Host "Moving VMs"
$VMs = Get-VM -Location $f -NoRecursion
foreach ($vm in $VMs) {
Try {
$vm_name = $vm.name -replace "\[", "``["
$targetVM = Get-VM -Name $vm_name -Location $targetRoot -NoRecursion -ErrorAction Stop
if ($targetVM.Length -gt 1) {
Write-Host "Multiple VMs Error"
throw("Multiple VMs found")
}
else {
$moveJob = Move-VM $targetVM -InventoryLocation $targetFolder
Write-Host "== Move VM: " $t.name "/" $from_name "<<" $vm.name
}
}
Catch {
#Write-Host "Skip VM:" $vm.name
}
}
}
Create-SubFolders -f $f -t $targetFolder -targetRoot $targetRoot
}
# Cycles through subfolders and creates them
Function Create-SubFolders($f, $t, $targetRoot) {
$subFolders = Get-Folder -Location $f
foreach ($folder in $subFolders) {
Create-Folder -f $folder -t $t -targetRoot $targetRoot
}
}
# MAIN
$sourceLocation = Get-folder -Server $srcVc -Name vm | Where-Object { $_.Parent -match "^$($sourceDatacenterName)$" }
$targetLocation = Get-folder -Server $dstVc -Name vm | Where-Object { $_.Parent -match "^$($targetDatacenterName)$" }
$sourceRootFolders = Get-Folder -Server $srcVc | Where-Object { $_.Parent -eq $sourceLocation -and $_.Type -eq "VM" }
# Goes through all root folders in sourceDatacenter
foreach ($folder in $sourceRootFolders) {
Create-Folder -f $folder -t $targetLocation -targetRoot $targetLocation
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment