function Get-FolderByPath{
<# .SYNOPSIS Retrieve folders by giving a path .DESCRIPTION The function will retrieve a folder by it's path. The path can contain any type of leave (folder or datacenter).
.NOTES Author: Luc Dekens .PARAMETER Path The path to the folder. This is a required parameter. .PARAMETER Path The path to the folder. This is a required parameter.
.PARAMETER Separator The character that is used to separate the leaves in the path. The default is '/' .EXAMPLE PS> Get-FolderByPath -Path "Folder1/Datacenter/Folder2"
.EXAMPLE
PS> Get-FolderByPath -Path "Folder1>Folder2" -Separator '>'
#>
param(
[CmdletBinding()]
[parameter(Mandatory = $true)]
[System.String[]]${Path},
[char]${Separator} = '/'
)
process{
if((Get-PowerCLIConfiguration).DefaultVIServerMode -eq "Multiple"){
$vcs = $defaultVIServers
}
else{
$vcs = $defaultVIServers[0]
}
foreach($vc in $vcs){
foreach($strPath in $Path){
$root = Get-Folder -Name Datacenters -Server $vc
$strPath.Split($Separator) | %{
$root = Get-Inventory -Name $_ -Location $root -Server $vc -NoRecursion
if((Get-Inventory -Location $root -NoRecursion | Select -ExpandProperty Name) -contains "vm"){
$root = Get-Inventory -Name "vm" -Location $root -Server $vc -NoRecursion
}
}
$root | where {$_ -is [VMware.VimAutomation.ViCore.Impl.V1.Inventory.FolderImpl]}|%{
Get-Folder -Name $_.Name -Location $root.Parent -NoRecursion -Server $vc
}
}
}
}
}
# move the vm's to correct location
$VMfolder = @()
$VMfolder = import-csv "f:\vms-with-FolderPath.csv" | Sort-Object -Property Path
foreach($guest in $VMfolder){
$key = @()
$key = Split-Path $guest.Path | split-path -leaf
if ($key -eq $datacenter) {
Write-Host "Root folder $guest.path"
Move-VM (Get-VM $guest.Name) -Destination (Get-folder $key)
}
else
{
Move-VM (Get-VM $guest.Name) -Destination "VM"
}
}
------------------------------------------------------------------------------------------------------
I have modified the Script as per your instruction. after ran the script i got the output as attached and task is triggered in VC but none of the vm is moved to destination folder
CSV file as below:
Name | Path |
SRV2012-R2-1 | DC1\prd |
srv2008-r2-1 | DC1\pordvm\prd |
srv2016-gui-1 | DC1\VMS\test-VM |