Automation

 View Only
Expand all | Collapse all

Script error when trying to move vms to their dedicated folders

  • 1.  Script error when trying to move vms to their dedicated folders

    Posted Oct 22, 2018 09:58 AM

    Hello,

    I am having issues when using a script to move VMs from the Discovered VMs folder to their dedicated VM folders as they were on the old vCenter. I already recreated the folder structure on the new vCenter.

    The csv from where i am importing is on the form:

    Name  Path

    vm1     DatacenterFolderName\folder1\folder2\vm1

    vm2     DatacenterFolderName\folder2\folder3\vm2 etc

    The script is the following:

    Get-Module -Name VMware* -ListAvailable | Import-Module

    If ($globale:DefaultVIServers ) {

    Disconnect-VIServer -Server $global:DefaultVIServers -Force

    }

    $destVI = Read-Host "Please enter name or IP address of the destination Server"

    $datacenter = Read-Host "DataCenter name in VC"

    $creds = get-credential

    connect-viserver -server $destVI -Credential $creds

    # move the vm's to correct location

    $VMfolder = @()

    $VMfolder = import-csv "c:\csv-files\test\04-$($datacenter)-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 "vm"

    }

    else

    {

    Move-VM (Get-VM $guest.Name) -Destination (Get-folder $key)

    }

    }

    Disconnect-VIServer "*" -Confirm:$False

    and the error i am getting is the following:

    Move-VM : 10/19/2018 7:50:24 AM Move-VM Server task failed: The request refers to an unexpected or unknown type.

    At C:\Users\username\Desktop\CheapDisasterRecovery\import-05-move-vms-folders.ps1:27 char:3

    +         Move-VM (Get-VM $guest.Name) -Destination (Get-folder $key)

    +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        + CategoryInfo          : NotSpecified: (:) [Move-VM], VimException

        + FullyQualifiedErrorId : Security_Impl_TaskResultConverter_TaskNotSucceeded,VMware.VimAutomation.ViCore.Cmdlets.Commands.MoveVM

    Can someone let me know what i am doing wrong or if there is something that needs to be modified to make it work?

    The original vCenter is 5.5 and the destination vCenter is 6.5.

    Thank you.



  • 2.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 22, 2018 10:17 AM

    If you are using a recent PowerCLI version, you have to use the InventoryLocation parameter to move a VM to a VM type folder.

    Which PowerCLI version are you using?



  • 3.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 22, 2018 10:25 AM

    Hi Luc, thanks so much for replying.

    This is what i get when list the modules:

    PS C:\Windows\system32> Get-Module -ListAvailable -Name VMware*

        Directory: C:\Program Files\WindowsPowerShell\Modules

    ModuleType Version    Name                                ExportedCommands

    ---------- -------    ----                                ----------------

    Script     6.7.0.8... VMware.DeployAutomation             {Add-DeployRule, Add-ProxyServer, Add-ScriptBundle, Copy-D...

    Script     6.7.0.8... VMware.ImageBuilder                 {Add-EsxSoftwareDepot, Add-EsxSoftwarePackage, Compare-Esx...

    Manifest   11.0.0.... VMware.PowerCLI

    Script     6.7.0.1... VMware.Vim

    Script     11.0.0.... VMware.VimAutomation.Cis.Core       {Connect-CisServer, Disconnect-CisServer, Get-CisService}

    Script     11.0.0.... VMware.VimAutomation.Cloud          {Add-CIDatastore, Connect-CIServer, Disconnect-CIServer, G...

    Script     11.0.0.... VMware.VimAutomation.Common

    Script     11.0.0.... VMware.VimAutomation.Core           {Add-PassthroughDevice, Add-VirtualSwitchPhysicalNetworkAd...

    Script     7.6.0.1... VMware.VimAutomation.HorizonView    {Connect-HVServer, Disconnect-HVServer}

    Script     10.0.0.... VMware.VimAutomation.License        Get-LicenseDataManager

    Script     11.0.0.... VMware.VimAutomation.Nsxt           {Connect-NsxtServer, Disconnect-NsxtServer, Get-NsxtService}

    Script     11.0.0.... VMware.VimAutomation.Sdk            {Get-ErrorReport, Get-PSVersion, Get-InstallPath}

    Script     11.0.0.... VMware.VimAutomation.Security       {Get-SecurityInfo, Get-VTpm, Get-VTpmCertificate, Get-VTpm...

    Script     10.0.0.... VMware.VimAutomation.Srm            {Connect-SrmServer, Disconnect-SrmServer}

    Script     11.0.0.... VMware.VimAutomation.Storage        {Add-KeyManagementServer, Copy-VDisk, Export-SpbmStoragePo...

    Script     1.3.0.0    VMware.VimAutomation.StorageUtility Update-VmfsDatastore

    Script     11.0.0.... VMware.VimAutomation.Vds            {Add-VDSwitchPhysicalNetworkAdapter, Add-VDSwitchVMHost, E...

    Script     11.0.0.... VMware.VimAutomation.Vmc            {Connect-Vmc, Disconnect-Vmc, Get-VmcSddcNetworkService, G...

    Script     10.0.0.... VMware.VimAutomation.vROps          {Connect-OMServer, Disconnect-OMServer, Get-OMAlert, Get-O...

    Script     6.5.1.7... VMware.VumAutomation                {Add-EntityBaseline, Copy-Patch, Get-Baseline, Get-Complia...

    So what do i have to replace in the script to make it work?



  • 4.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 22, 2018 10:35 AM

    Do i need to replace the -Destination parameter with -InventoryLocation ?



  • 5.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 22, 2018 10:44 AM

    No, due to a "feature" you also have to use the Destination parameter.
    But you can point Destination to the same ESXi node where the VM is already running.

    Something like this seems to work for me.

    $vm = Get-VM -Name $guest.Name

    $folder = Get-Folder -Name $key -Type VM

    Move-VM -VM $vm -Destination $vm.VMHost -InventoryLocation $folder



  • 6.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 22, 2018 11:32 AM

    Thanks for the reply and clarification.

    Do i replace the whole if / else sequence in the script or just the lines containing the Move-VM command? I am a bit confused as to what do i need to modify in the script... Do i need to also have a column in the CSV with the host where the VM resides? the exported csv only contains the vm name and path as described in the original post.



  • 7.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 22, 2018 11:52 AM

    You only should replace the single Move-VM line in your Else-block with these lines.

    No need to add a column, the Get-VM will return an object that shows where the VM is running in the VMHost property.



  • 8.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 22, 2018 01:18 PM

    I did that initially but it throws another error and i thought am not doing something right and something else must be modified.

    This is the error i am getting now, with only the single Move VM line replaced in the else block from the script:

    Move-VM : 10/22/2018 9:13:52 AM Move-VM Value cannot be found for the mandatory parameter VM

    At C:\Users\username\Desktop\CheapDisasterRecovery\import-05-move-vms-folders.ps1:29 char:9

    +         Move-VM -Destination $vm.VMHost -InventoryLocation $folder

    +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        + CategoryInfo          : NotSpecified: (:) [Move-VM], VimException

        + FullyQualifiedErrorId : Core_BaseCmdlet_UnknownError,VMware.VimAutomation.ViCore.Cmdlets.Commands.MoveVM

    Any thoughts?



  • 9.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 22, 2018 02:17 PM

    The Move-VM should of course include the VM parameter.

    I updated the code above.



  • 10.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 22, 2018 04:30 PM

    Thank you so much for your help. It is working as expected now.



  • 11.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 11:57 AM

    Hi Luc,

    The script works when moving the vms into unique folders, however when trying to move the vms into duplicate folder names from different paths it errors out like this:

    Move-VM : Cannot convert 'System.Object[]' to the type

    'VMware.VimAutomation.ViCore.Types.V1.Inventory.VIContainer' required by parameter

    'Destination'. Specified method is not supported.

    At C:\Users\username\Desktop\CheapDisasterRecovery\import-05-move-vms-folders.ps1:29 char:38

    +         Move-VM -VM $vm -Destination $vm.VMHost -InventoryLocation $f ...

    +                                      ~~~~~~~~~~

        + CategoryInfo          : InvalidArgument: (:) [Move-VM], ParameterBindingException

        + FullyQualifiedErrorId : CannotConvertArgument,VMware.VimAutomation.ViCore.Cmdlets.C

       ommands.MoveVM

    Any idea on how to correct this?



  • 12.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 12:22 PM

    Now i tried again with the unique folders and it is throwing the same error...



  • 13.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 12:41 PM

    I suspect that the $vm variable holds more than 1 VM.
    Can you check?



  • 14.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 01:03 PM

    I modified the csv and I tried to move a single vm now which has unique name within the whole vcenter and it is erroring out.

    This is the code i tried with it:

    Get-Module -Name VMware* -ListAvailable | Import-Module

    If ($globale:DefaultVIServers ) {

    Disconnect-VIServer -Server $global:DefaultVIServers -Force

    }

    $destVI = Read-Host "Please enter name or IP address of the destination Server"

    $datacenter = Read-Host "DataCenter name in VC"

    $creds = get-credential

    connect-viserver -server $destVI -Credential $creds

    # move the vm's to correct location

    $VMfolder = @()

    $VMfolder = import-csv "C:\csv-files\test\04-$datacenter-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 "vm"

    }

    else

    {

    $vm = Get-VM -Name $guest.Name

            $folder = Get-Folder -Name $key -Type VM

            Move-VM -VM $vm -Destination $vm.VMHost -InventoryLocation $folder

    }

    }

    Disconnect-VIServer "*" -Confirm:$False

    Still no luck... Either that or i am not sure exactly what 1 VM into the $vm variable means... what do i need to check by that?



  • 15.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 01:12 PM

    You could be connected multiple times. CHeck what is in $global:defaultviservers

    You could have multiple VMs with the same displayname in the environment.

    How many objects does this return (use the name of the single VM you tested with)?

    Get-VM -Name <your-VM>



  • 16.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 01:21 PM

    Hello,

    Nope, just a single object returned for each of the commands.

    PS C:\Windows\system32> $global:defaultviservers

    Name                           Port  User                         

    ----                           ----  ----                         

    prdvcsa                      443   DOMAIN\malbu             

    PS C:\Windows\system32> Get-VM -Name malbu-vm

    Name                 PowerState Num CPUs MemoryGB      

    ----                 ---------- -------- --------      

    malbu-vm             PoweredOn  2        6.000         



  • 17.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 01:39 PM

    I added some debugging lines.

    Can you run this version, and tell me what is shown on the console?

     

    Get-Module -Name VMware* -ListAvailable | Import-Module

    If ($global:DefaultVIServers ) {

        Disconnect-VIServer -Server $global:DefaultVIServers -Force

    }

     

    $destVI = Read-Host "Please enter name or IP address of the destination Server"

    $datacenter = Read-Host "DataCenter name in VC"

    $creds = Get-Credential

    connect-viserver -server $destVI -Credential $creds

     

    # move the vm's to correct location

    $VMfolder = @()

    $VMfolder = Import-Csv "C:\csv-files\test\04-$datacenter-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 "vm"

        }

        else

        {

            $vm = Get-VM -Name $guest.Name

            $folder = Get-Folder -Name $key -Type VM

           

            Write-Host "VM : $($vm.Count)"

            Write-Host "ESX : $($VM.VMHost.Name -join '|')"

     

            Move-VM -VM $vm -Destination $vm.VMHost -InventoryLocation $folder

        }

    }

     

    Disconnect-VIServer "*" -Confirm:$False

     



  • 18.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 01:56 PM

    I ran your version and it's working...seriously, i don't understand this anymore... This is the output with the debugging:

    PS C:\Windows\system32> C:\Users\username\Desktop\CheapDisasterRecovery\import-05-move-vms-folders-debugging.ps1

    Please enter name or IP address of the destination Server: prdvcsa

    DataCenter name in VC: Corporate

    cmdlet Get-Credential at command pipeline position 1

    Supply values for the following parameters:

    Name                           Port  User                         

    ----                           ----  ----                         

    prdvcsa                      443   DOMAIN\malbu             

    VM : 1

    ESX : prd1.domain.com

    PowerState              : PoweredOn

    Version                 : v10

    HardwareVersion         : vmx-10

    Notes                   :

    Guest                   : malbu-vm:Microsoft Windows 7 (64-bit)

    NumCpu                  : 2

    CoresPerSocket          : 1

    MemoryMB                : 6144

    MemoryGB                : 6

    VMHostId                : HostSystem-host-13

    VMHost                  : prd1.domain.com

    VApp                    :

    FolderId                : Folder-group-v2060

    Folder                  : Employees

    ResourcePoolId          : ResourcePool-resgroup-30

    ResourcePool            : Resources

    PersistentId            : 5028db3d-0246-08c0-d83c-1103dd2c7a9e

    UsedSpaceGB             : 54.409996171481907367706298828

    ProvisionedSpaceGB      : 66.109215467236936092376708984

    DatastoreIdList         : {Datastore-datastore-1664}

    HARestartPriority       : ClusterRestartPriority

    HAIsolationResponse     : AsSpecifiedByCluster

    DrsAutomationLevel      : AsSpecifiedByCluster

    VMSwapfilePolicy        : Inherit

    VMResourceConfiguration : CpuShares:Normal/2000 MemShares:Normal/61440

    GuestId                 : windows7_64Guest

    Name                    : malbu-vm

    CustomFields            : {[XdConfig, ]}

    ExtensionData           : VMware.Vim.VirtualMachine

    Id                      : VirtualMachine-vm-1558

    Uid                     : /VIServer=domain\malbu@prdvcsa:443/VirtualMachine=VirtualM

                              achine-vm-1558/

    PS C:\Windows\system32>



  • 19.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 02:00 PM

    Can you attach your last version of the script as a file (bottom right - attach button)?



  • 20.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 02:10 PM
      |   view attached

    Sure, this is the script i last ran before the debugging one you sent.

    Attachment(s)



  • 21.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 04:05 PM

    I don't see any obvious differences.

    Did you test run the last version several times?

    Does it always work?



  • 22.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 04:55 PM

    I ran your debug version against the production list so to speak and half of the list worked. From what i checked, the other half of the list contains folders that are present in multiple paths, and those are still erroring out.

    The error is mostly the same (this time is inventorylocation related parameter):

    Move-VM : Cannot convert 'System.Object[]' to the type

    'VMware.VimAutomation.ViCore.Types.V1.Inventory.FolderContainer' required by parameter

    'InventoryLocation'. Specified method is not supported.

    At

    C:\Users\username\Desktop\CheapDisasterRecovery\import-05-move-vms-folders-debugging.ps1:61

    char:68

    + ...    Move-VM -VM $vm -Destination $vm.VMHost -InventoryLocation $folder

    +                                                                   ~~~~~~~

        + CategoryInfo          : InvalidArgument: (:) [Move-VM], ParameterBindingException

        + FullyQualifiedErrorId : CannotConvertArgument,VMware.VimAutomation.ViCore.Cmdlets.C

       ommands.MoveVM



  • 23.  RE: Script error when trying to move vms to their dedicated folders
    Best Answer

    Posted Oct 25, 2018 07:16 PM

    Your script will not work when you have two subfolders with the same name.

    DC\Folder1\TestFolder\vm2

    DC\Folder2\TestFolder\vm2

    To avoid that I have added a modified version of my Get-FolderByPath function.

    Can you try with this version.

    function Get-FolderByPath{

       param(

       [CmdletBinding()]

       [parameter(Mandatory = $true)]

       [System.String[]]${Path},

       [char]${Separator} = '/'

       )


       process{

       foreach($strPath in $Path){

       $root = Get-Folder -Name Datacenters

       $strPath.Split($Separator) | %{

       $root = Get-Inventory -Name $_ -Location $root -NoRecursion

       if((Get-Inventory -Location $root -NoRecursion | Select -ExpandProperty Name) -contains "vm"){

       $root = Get-Inventory -Name "vm" -Location $root -NoRecursion

       }

       }

       $root | where {$_ -is [VMware.VimAutomation.ViCore.Impl.V1.Inventory.FolderImpl]}|%{

       Get-Folder -Name $_.Name -Location $root.Parent -NoRecursion

       }

       }

       }

    }


    Get-Module -Name VMware* -ListAvailable | Import-Module

    If ($globale:DefaultVIServers ) {

       Disconnect-VIServer -Server $global:DefaultVIServers -Force

    }

    $destVI = Read-Host "Please enter name or IP address of the destination Server"

    $creds = Get-Credential

    connect-viserver -server $destVI -Credential $creds

    # move the vm's to correct location

    $VMfolder = Import-Csv "C:\csv-files\test\04-$datacenter-vms-with-FolderPath.csv" | Sort-Object -Property Path

    foreach($guest in $VMfolder){

       $key =  Split-Path $guest.Path

       $keyFolder = Get-FolderByPath -Path $key -Separator '\'

       $vm = Get-VM -Name $guest.Name

       Move-VM -VM $vm -Destination $vm.VMHost -InventoryLocation $keyFolder

    }

    Disconnect-VIServer "*" -Confirm:$False



  • 24.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 25, 2018 07:19 PM

    Sure, i will run this first thing when i get back to the office and let you know how it goes.

    Thank you for your patience and help Luc, much appreciated.



  • 25.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 26, 2018 08:08 AM

    Hello Luc,

    I ran the script and it worked flawlessly. Man, I cannot thank you enough for your help with this issue!

    Really appreciate it!



  • 26.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 28, 2023 09:09 AM

     

     

    Hi LucD,

    Thanks for this. 

    I just wanted to advise on the issues I had, and see if they affected anyone else.

    I had to change the [char]${Separator} = '/' to [char]${Separator} = '\' in the get-folderbypath function, as the $key = Split-Path $guest.Path line converts the / to \, and then errors if the / is not replaced with \.

    I also noticed that you have an rogue e in the $global:DefaultVIServers line, you have $globale:DefaultVIServers.

    The below, worked for me:

    function Get-FolderByPath{
    param(

    [CmdletBinding()]

    [parameter(Mandatory = $true)]

    [System.String[]]${Path},

    [char]${Separator} = '\'

    )


    process{

    foreach($strPath in $Path){

    $root = Get-Folder -Name Datacenters

    $strPath.Split($Separator) | %{

    $root = Get-Inventory -Name $_ -Location $root -NoRecursion

    if((Get-Inventory -Location $root -NoRecursion | Select -ExpandProperty Name) -contains "vm"){

    $root = Get-Inventory -Name "vm" -Location $root -NoRecursion

    }

    }

    $root | where {$_ -is [VMware.VimAutomation.ViCore.Impl.V1.Inventory.FolderImpl]}|%{

    Get-Folder -Name $_.Name -Location $root.Parent -NoRecursion

    }

    }

    }

    }


    Get-Module -Name VMware* -ListAvailable | Import-Module

    If ($global:DefaultVIServers ) {

    Disconnect-VIServer -Server $global:DefaultVIServers -Force -Confirm:$false

    }

    $destVI = Read-Host "Please enter name or IP address of the destination Server"

    $creds = Get-Credential

    connect-viserver -server $destVI -Credential $creds

    # move the vm's to correct location

    $VMfolder = Import-Csv "C:\Scripts\AdminTasks\Powercli\Folders\VM_folderpaths_import_migration_test.csv" | Sort-Object -Property Path

    foreach($guest in $VMfolder)
    {
    # This converts the format of the path from folder/folder to folder\folder, and why the seperator must be \ in the function
    $key = Split-Path $guest.Path
    write-host -ForegroundColor cyan $key

    $keyFolder = Get-FolderByPath -Path $key -Separator '\'

    $vm = Get-VM -Name $guest.Name

    Move-VM -VM $vm -Destination $vm.VMHost -InventoryLocation $keyFolder | out-null
    }

    Disconnect-VIServer "*" -Confirm:$False

     



  • 27.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 05:54 PM

    New to scripting...  I have an exported .csv in vCenter 5.5 and moves hosts to vCenter 6.5 now.  It that ran perfect on the export.  But I cannot get the below to run in my vCenter6.  Here is the output... 

      .csv contents...  

    NameBlueFolderPath
    Demo16/Demos
    Demo1/Demos
    Demo17/Demos
    Demo27/Demos
    Demo15/Demos

    I keep getting errors on my script... 

    New-Folder : Cannot convert 'System.Object[]' to the type 'VMware.VimAutomation.ViCore.Types.V1.Inventory.VIContainer' required by parameter 'Location'. Specified method is not supported.

    At line:11 char:55

    +             $location = New-Folder -Name $_ -Location $location

    +                                                       ~~~~~~~~~

        + CategoryInfo          : InvalidArgument: (:) [New-Folder], ParameterBindingException

        + FullyQualifiedErrorId : CannotConvertArgument,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewFolder

    Here is my script... 

    $newDatacenter = "Boston"

    $newFolder = "Folder1"

    $startFolder = Get-Folder -Name "vm"

    Import-Csv "C:\scripts\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 $vm.VMHost -InventoryLocation $folder -Confirm:$false

        }

    }



  • 28.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 06:08 PM

    Did you check if there is perhaps an empty line the CSV file?

    Can you runt the following on that CSV file?

    Import-Csv "C:\scripts\vm-folder.csv" -UseCulture | %{

        Write-Host "$($_.Length) $($_.Name) $($_.BlueFolderPath)"

    }



  • 29.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 06:19 PM

    I do not see an empty line.  The results returned the following... 

    Demo16 /Demos

    Demo1 /Demos

    Demo17 /Demos

    Demo27 /Demos

    Demo15 /Demos



  • 30.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 06:36 PM

    Is that error repeated for every line in the CSV, or do you only see it once?



  • 31.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 06:45 PM

    Every line...

    Demo16               PoweredOn  2        4.000        

    New-Folder : Cannot convert 'System.Object[]' to the type 'VMware.VimAutomation.ViCore.Types.V1.Inventory.VIContainer' required by parameter 'Location'. Specified method is not supported.

    At line:11 char:55

    +             $location = New-Folder -Name $_ -Location $location

    +                                                       ~~~~~~~~~

        + CategoryInfo          : InvalidArgument: (:) [New-Folder], ParameterBindingException

        + FullyQualifiedErrorId : CannotConvertArgument,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewFolder

    Demo1                PoweredOn  2        8.000        

    New-Folder : Cannot convert 'System.Object[]' to the type 'VMware.VimAutomation.ViCore.Types.V1.Inventory.VIContainer' required by parameter 'Location'. Specified method is not supported.

    At line:11 char:55

    +             $location = New-Folder -Name $_ -Location $location

    +                                                       ~~~~~~~~~

        + CategoryInfo          : InvalidArgument: (:) [New-Folder], ParameterBindingException

        + FullyQualifiedErrorId : CannotConvertArgument,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewFolder

    Demo17               PoweredOn  2        6.000        

    New-Folder : Cannot convert 'System.Object[]' to the type 'VMware.VimAutomation.ViCore.Types.V1.Inventory.VIContainer' required by parameter 'Location'. Specified method is not supported.

    At line:11 char:55

    +             $location = New-Folder -Name $_ -Location $location

    +                                                       ~~~~~~~~~

        + CategoryInfo          : InvalidArgument: (:) [New-Folder], ParameterBindingException

        + FullyQualifiedErrorId : CannotConvertArgument,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewFolder

    Demo27               PoweredOff 2        4.000        

    New-Folder : Cannot convert 'System.Object[]' to the type 'VMware.VimAutomation.ViCore.Types.V1.Inventory.VIContainer' required by parameter 'Location'. Specified method is not supported.

    At line:11 char:55

    +             $location = New-Folder -Name $_ -Location $location

    +                                                       ~~~~~~~~~

        + CategoryInfo          : InvalidArgument: (:) [New-Folder], ParameterBindingException

        + FullyQualifiedErrorId : CannotConvertArgument,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewFolder

    Demo15               PoweredOn  2        10.000       

    New-Folder : Cannot convert 'System.Object[]' to the type 'VMware.VimAutomation.ViCore.Types.V1.Inventory.VIContainer' required by parameter 'Location'. Specified method is not supported.

    At line:11 char:55

    +             $location = New-Folder -Name $_ -Location $location

    +                                                       ~~~~~~~~~

        + CategoryInfo          : InvalidArgument: (:) [New-Folder], ParameterBindingException

        + FullyQualifiedErrorId : CannotConvertArgument,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewFolder

    In the vCenter recent tasks it shows this...



  • 32.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 07:03 PM

    The Move-VM error is a result from the target folder not being there (due to the other error).

    The 1st error seems to indicate that the value on the Name parameter of the New-Folder cmdlet is an array instead of a string.

    I don't really see how that can happen when loop through the output of the Import-Csv.

    Can you just do a

    Import-Csv "C:\scripts\vm-folder.csv" -UseCulture

    And check if the column headers are also shown?



  • 33.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 07:21 PM

    I do see column headers... 

     

    Name BlueFolderPath        
    ---- --------------        
    OZ-BDC-Demo-27                 /Demos                
    OZ-BDC-Demo-25                 /Demos                
    OZ-BDC-Demo-24                 /Demos                
    OZ-BDC-Demo-23                 /Demos                
    OZ-BDC-Demo-22                 /Demos                
    OZ-BDC-Demo-21                 /Demos                
    OZ-BDC-Demo-18                 /Demos                
    OZ-BDC-Demo-19                 /Demos                
    OZ-BDC-Demo-16                 /Demos 


  • 34.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 07:43 PM

    But wait a minute, I'm looking at the wrong parameter, it's the Location parameter that complain about getting an array.

    Do you by any chance have multiple Datacenters defined, or are you connected to more than vSPhere server?

    Does the following return 1 folder or more?

    Get-Folder -Name vm



  • 35.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 07:47 PM

    I'm confused as to why this is my result... 

    PS C:\scripts> Get-Folder -Name vm

    Name                           Type          

    ----                           ----          

    vm                             VM            

    vm                             VM            

    vm                             VM            

    vm                             VM            

    vm                             VM            

    vm                             VM



  • 36.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 07:52 PM

    Can you check the following

    $global:defaultviservers

    Get-Datacenter



  • 37.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 07:54 PM

    I show 1 vCenter connected to my session.  The correct one.

    But it is showing all 6 of my DataCenters in Get-Datacenter



  • 38.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 08:00 PM

    And that is causing the issue.

    There is a hidden folder named 'vm' under each Datacenter.

    Change the $startFolder line like this

    $startFolder = Get-Folder -Name "vm" -Location $newDatacenter



  • 39.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 08:11 PM

    So that worked and it creates the folders! It began creating the folders. 

    Problem now is I am not getting any script errors...  but the VMs aren't moving.  The only error now is in vCenter...



  • 40.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 08:17 PM

    Where are these VMs located?

    Are these folders accessible from the cluster on which the VMs are running?



  • 41.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 08:28 PM

    Update...  when I run the script from the ./script it actually runs!

    My next problem is when it gets to a folder that is more than one level deep it errors with the same error.

    /Clients/Bridge-Backups


  • 42.  RE: Script error when trying to move vms to their dedicated folders

    Posted Sep 30, 2019 08:35 PM

    Do you still do the move like this?
    Because I don't see in the code you included where $folder is initialised.

    Shouldn't that be $tgtFolder instead of $folder?

        if($vm){

            Move-VM -VM $vm -Destination $vm.VMHost -InventoryLocation $folder -Confirm:$false

        }



  • 43.  RE: Script error when trying to move vms to their dedicated folders

    Posted Oct 01, 2019 03:44 PM

    Thank you so much for all your help on this!  Here is the final version that worked perfectly.  Created folders and moved VMs... 

    $newDatacenter = "blahblah"

    $newFolder = "Folder1"

    $startFolder = Get-Folder -Name "vm" -Location $newDatacenter

    Import-Csv "C:\scripts\vCenter5_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 $vm.VMHost -InventoryLocation $location -Confirm:$false

        }

    }