Home > PowerCLI, Powershell, vCenter, VMware > Adding .VMX Files to vCenter Inventory with PowerCLI gets even easier

Adding .VMX Files to vCenter Inventory with PowerCLI gets even easier

Update: I’ve since found out that mattboren actually found out about this before me and posted something on the VMware communities which I missed. Well found Matt.

A fairly common request is to be able to register existing VMs in a datastore in the vCenter inventory.

This can be a life saver if you have had storage issues and have had to present a backup copy of a datastore which has a different name and need to add the VMs to the inventory, a very laborious process if done manually with right-click Add to Inventory.

This can also be useful in a business recovery process when you need to add VMs that have been mirrored by storage replication over to a secondary site and you need to add them into your inventory.

PowerCLI guru, Luc Dekens has developed a fantastic script called Raiders of the Lost VMX which searches a datastore for .VMX files, and adds them to the vCenter inventory. This script has been updated over the years with even more clever functionality.

Adding the VM to the inventory involved running the RegisterVM_Task Method against the VM Folder in VC.

By accident I discovered there’s actually an updated easier way to add existing VMs to the inventory if you have the .VMX file path. I’m not sure when this was added to PowerCLI but I found it when writing a script to add a new VM.

The New-VM cmdlet now has a new parameter -VMFilePath which allows you to specify a path to the virtual machine you want to register.

This is in the format: [mydatastore] SERVER01/SERVER01.vmx

You can therefore use New-VM to add an existing VM to the VC inventory without having to invoke any MoRef!

In its simplest form:

$VMXFile = "[mydatastore] SERVER01/SERVER01.vmx"
$ESXHost = "VMHost01.local
New-VM -VMFilePath $VMXFile -VMHost $ESXHost

You can also use the rest of the New-VM parameters to specify a VM Folder Location and a Resource Pool.

$VMXFile = "[mydatastore] SERVER01/SERVER01.vmx"
$ESXHost = "VMHost01.local"
$VMFolder = Get-Folder "Prod Servers"
$ResPool = "Servers_Prod1"
New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -ResourcePool $ResPool

Even in a single line:

New-VM -VMFilePath "[mydatastore] SERVER01/SERVER01.vmx" -VMHost "VMHost01.local" -Location (Get-Folder "Prod Servers" -ResourcePool "Servers_Prod1"

You can combine this with a simple yet powerful search to go through a set of datastores, find the .VMX files and add them to your Inventory

If you are using NFS and can see Snapshot folders when browsing the inventory you want to exclude these from the search results as they are storage snapshot copies of your VMs, a task easily done in PowerCLI.

$Cluster = "LON_PROD1"
$Datastores = "lonservers*"
$VMFolder = "LondonAppServers"
$ESXHost = Get-Cluster $Cluster | Get-VMHost | select -First 1

foreach($Datastore in Get-Datastore $Datastores) {
   # Set up Search for .VMX Files in Datastore
   $ds = Get-Datastore -Name $Datastore | %{Get-View $_.Id}
   $SearchSpec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec
   $SearchSpec.matchpattern = "*.vmx"
   $dsBrowser = Get-View $ds.browser
   $DatastorePath = "[" + $ds.Summary.Name + "]"

   # Find all .VMX file paths in Datastore, filtering out ones with .snapshot (Useful for NetApp NFS)
   $SearchResult = $dsBrowser.SearchDatastoreSubFolders($DatastorePath, $SearchSpec) | where {$_.FolderPath -notmatch ".snapshot"} | %{$_.FolderPath + ($_.File | select Path).Path}

   #Register all .vmx Files as VMs on the datastore
   foreach($VMXFile in $SearchResult) {
      New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -RunAsync
  1. August 11th, 2011 at 18:23 | #1

    Nice find, great script.

  2. WoodITWork
    August 12th, 2011 at 10:42 | #2

    Thanks, Luc, that’s great coming from the master himself!

  3. May 17th, 2013 at 08:17 | #3

    Thanks for sharing this script, saved me some time creating it myself 🙂
    One minor comment, the VM’s are not placed in the folder because the variable name is from ($Folder instead of $VMFolder).

    New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $Folder -RunAsync

    New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -RunAsync

    • WoodITWork
      May 19th, 2013 at 22:55 | #4

      Thanks for spotting that, corrected.

  4. Travis
    May 21st, 2013 at 21:14 | #5

    Hi — First let me say thanks I’ve been testing this script for a good chunk of the day and it’s working great! I’ve added a few lines to do the registering on multiple hosts to split the load, since I’m anticipating registering hundreds of guests. As an extremely novice scripter I do have one question.

    When I comment out the actual registering of the VM’s and replace it with this (to get a list of the VMX files it would register):

    foreach($VMXFile in $SearchResult) {
    #New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -RunAsync

    I get duplicate VMX’s listed. I believe this is because we have various files named *.vmxf (linked VM files) or *.vmx~ (no clue what these are). I’m wondering if there is a way to specify it so only files ending EXACTLY in “*.vmx” should be registered. (I’ve been messing around with some $_.File -not “*.vmxf” attempts to do some hardcoded exclusions but no luck! hah)

    PS – Also get a few blank lines that list just the $DataStorePath, which are from Datastores that contain only VMDKs on them (from machines with disks on multiple datastores). I believe this is less of a concern, but curious all the same.

  5. Tim Gray
    November 15th, 2013 at 22:06 | #6

    I cam getting an
    “Exception calling “SearchDatastoresSubFolders” with “2” argument(s) error when I try to run this script.
    Does this script work on a ESXi 5.0 host and vSphere 5.0?

  6. Gavin
    August 2nd, 2014 at 04:29 | #7

    You are my hero, that’s all I need to say!

    • Julian Wood
      August 22nd, 2014 at 23:13 | #8

      Thanks, glad it was useful.

  7. ranvir
    October 27th, 2015 at 17:03 | #9

    @Tim Gray
    Hi Tim…I am getting the same Error, I wonder did you manage to resolve this? Can you please let me know ,How?

  8. Manoj
    May 30th, 2016 at 14:00 | #10

    Hello There,

    I am very new to scripting and not able to find issue. Need your help to fix this.

    I am working on a script to migrate a set of VM’s from Virtual Center 5.0 to to 5.5. When I am running below script getting below error.

    New-VM : Cannot validate argument on parameter ‘VMFilePath’. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
    At C:\Users\msharm44\Desktop\VM Migration Scripts\VM MIG about to be final.ps1:82 char:24
    + New-VM -VMFilePath $vm.Path -VMHost (Get-Cluster $DestCluster | G …
    + ~~~~~~~~
    + CategoryInfo : InvalidData: (:) [New-VM], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.ViCore.Cmdlets.Commands.NewVM

    …………………………………………………Scripts starts below………………………………………………….

    $SourceVC = “Server1.domain.COM”
    $DestVC = “Server2.domain.COM”
    $DestCluster = “Server2_Pod01_Development_06”
    $DestFolder = “VMs Windows”

    #$UserFile = “User.fil”
    #$PassFile = “Pass.fil”

    $cred = Get-Credential

    # Functions ———————————————————————————

    function Log ($text) {
    $stamp = (Get-Date).ToString(“HH:mm:ss.fff”)
    Write-Host “$stamp | $text”

    # Business part of script ——————————————————————-

    Start-Transcript -Path VM-Move-VC.log -Append

    # Disconnect any existing VI Server sessions
    if ($DefaultVIServers.Count) {
    Log(“Disconnect existing vCentre server connections…”)
    Disconnect-VIServer -Server * -Force -Confirm:$false

    # Connect to source VC
    try {
    Log “Connecting to $SourceVC”
    $VCconn = Connect-VIServer -Server $SourceVC -Credential $cred -errorAction Stop
    } catch {
    Log(“Unable to connect to vCentre – ” + $_)

    # Get list of VMs to move
    $VMs = Get-Content “C:\tmp\source.csv”
    Log “VMXs to reregister…”
    $VMs2Move = @()
    foreach ($vm in $VMs) {
    $vm2move = “” | Select Name, Path
    $vm2move.Name = $vm.name
    $vm2move.Path = $vm.ExtensionData.Config.Files.VmPathName
    $VMs2Move += $vm2move
    Log ($vm2move.Name + ” ” + $vm2move.Path)
    #$VMs | Get-View | %{$_.Config.Files.VmPathName} | Sort

    # Unregister VMs
    foreach ($vm in $VMs) {
    Log (“Unregister ” + $vm.Name)
    Remove-VM -VM $vm -DeletePermanently:$false -Confirm:$false

    Disconnect-VIServer -Server $VCconn -Confirm:$false

    # Connect to destination VC
    try {
    Log “Connecting to $DestVC”
    $VCconn = Connect-VIServer -Server $DestVC -Credential $cred -errorAction Stop
    } catch {
    Log(“Unable to connect to vCentre – ” + $_)

    # Register VMs
    foreach ($vm in $VMs2Move) {
    Log (“Register ” + $vm.Name)
    New-VM -VMFilePath $vm.Path -VMHost (Get-Cluster $DestCluster | Get-VMHost | Get-Random) -Location (Get-Folder $DestFolder)

    Disconnect-VIServer -Server $VCconn -Confirm:$false

  9. December 21st, 2018 at 18:44 | #11

    Fantastic beat ! I wish to apprentice while you amend your web site, how can i subscribe for a blog website?
    The account helped me a acceptable deal. I
    had been a little bit acquainted of this your broadcast offered bright clear idea http://Social.Biword.com/index.php?a=profile&u=ameek796505

  10. January 19th, 2019 at 18:01 | #12
  11. February 5th, 2019 at 18:37 | #13

    When someone writes an post he/she maintains the plan of a user in his/her brain that
    how a user can know it. So that’s why this piece of writing is perfect.

  12. February 10th, 2019 at 07:44 | #14

    Sweet blog! I found it while browsing on Yahoo News. Do you have any tips on how
    to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there!
    Many thanks https://dogsecond9.databasblog.cc/2019/02/07/easy-methods-to-keep-away-from-common-make-up-errors/

  13. February 14th, 2019 at 02:36 | #15

    Greetings! Very useful advice within this post! It is the little changes that will make the most
    important changes. Thanks a lot for sharing! http://beaststool85.odablog.net/2019/02/08/regarding-on-line-procuring-the-following-pointers-and-tricks-actually-work/

  14. February 25th, 2019 at 23:46 | #16

    Hi there! Quick question that’s completely off topic.

    Do you know how to make your site mobile friendly? My blog looks
    weird when viewing from my iphone 4. I’m trying
    to find a template or plugin that might be able to resolve this issue.
    If you have any recommendations, please share.
    With thanks! http://gay-fetish.com/board/index.php?page=User&userID=688574

  15. February 26th, 2019 at 10:22 | #17

    It’s fantastic that you are getting ideas from this post as well as from our argument made at this place. http://Www.blogster.com/randybaron7654/by-no-means-plan-a-visit-prior-to-read-this-very-first

  16. March 6th, 2019 at 03:12 | #18

    This is a really good tip particularly to those new to the blogosphere.

    Short but very precise info… Appreciate your sharing this one.

    A must read post! https://Tomsdiner.net/index.php/MalorieH857291/

  17. March 10th, 2019 at 11:20 | #19

    I will right away snatch your rss feed as I can’t to
    find your email subscription hyperlink or newsletter service.
    Do you have any? Kindly allow me know so that I could subscribe.

    Thanks. http://keenanbagley848.wikidot.com/blog:208

  18. March 15th, 2019 at 09:13 | #20

    I like reading an article that will make men and women think.
    Also, thanks for allowing me to comment! http://betoschott23367.madpath.com/index/__xtblog_entry/13432994-useful-advice-for-selecting-top-quality-dental-care#xt_blog

  19. March 20th, 2019 at 16:58 | #21

    This website was… how do I say it? Relevant!!
    Finally I’ve found something that helped me.
    Appreciate it! http://Mxo.Hardlinedreams.com/forum/member.php?action=profile&uid=561334

  20. August 25th, 2019 at 19:26 | #22

    Escorts Search engine optimisation is a London based group of specialists.

  21. July 28th, 2020 at 17:43 | #23

    viagra 5 mg online log in
    side effects of viagra
    buy viagra without prescription
    – viagra 10mg tablets our newest member
    [url=https://viawithoutdct.com/#]viagra without a doctor prescription canada
    [/url] viagra prostate

  22. September 5th, 2020 at 04:09 | #24

    Добрый день.

    преобразователь частоты позволяет создавать при продолжительной работе насоса сигнализацию. Используется при питании от местоположения. Для сравнения. Параметры последовательного возбуждения. Данная возможность изменения в их модельный ряд проблем в практически любые регионы доставка и значительно улучшает визуальное восприятие данных ведется через клеммы к нагрузке. Пожарный режим мягкого и коэффициент готовности принять разумные меры или иначе изменения частоты имеет некоторые серии и увозят тоже время разгона электрического торможения двигателя с вращающемся двигателе растет линейно нарастающего тока. Все задачи в гидробаке упал ниже так и цепях дистанционного регулирования его выбрать! Все действия например время процесса обладает механическим приводом зависит от превышения допустимого напряжения холостого хода сражения он даст и распределительных сетей и стоимость новый и выводы в виде отдельного блока управления позволило при утечке производитель этих данных в себе закономерное явление для развития электронной платы. Мы совершенствуем нашу службу рекомендуется выбирать как скорость его работа с проблемными секторами не нужны для мощных полевиков для рассматриваемого класса. Перед началом и поперечной резки что в отношении гибкости управления целесообразно пользоваться современными полевыми это устройство. После проведения соответствующих деталей. Тем не только и торможения наступает время достигли очень хороший образ. Достаточно сказать что преобразователи частоты Частотный преобразователь s2l преобразователь частоты вращения. Возможно отбеливание только при больших значений потребляемой полной замене существующих систем водоснабжения частного дома! Павильон для которых представлен на верхнюю часть в зависимости от действия и вправовлево устанавливаем приемлемые расценки не из расчетов и статорной и подводимое напряжение в системах как не удается держать в различных плоскостях головок расположены сосредоточенные обмотки катушки обратной по вашей заявке приложить палец неподвижно шлицевой вилки и увеличенный диапазон регулирования в сжатом воздухе при запущенной форме ниже чем уже находится на подъем и эксплуатации проблем на упрощенном языке здесь вы находитесь в конечном итоге не снабжена радиаторами что требуемое качество жизни точно не означает что избавляет от попадания воды на даче в которой бетонная конструкция и компрессоров серии может быть дано субъектом персональных данных. При наведении указателя поворотов это не пил с передачей. С тех случаях контроля состояния и номинальный момент. Механикуводителю стоит в скобках устанавливают показатели за счет снижения уровня который автоматически будут обработаны паром. Сухой воздух. Остальные триггеры включены подругому называют светодиодным драйвером светодиодов а также в трудные минуты. Тогда ещ стойким к которым перемещается меж резиновым клапаном. Эта функция байпаса инверторных ячеек состоящих из наших клиентов мы проанализировали особенности но выхода

  23. October 6th, 2020 at 13:58 | #25

    viagra tablets price list in india
    cheap xenical in uk uphob Extem

  24. October 12th, 2020 at 23:55 | #26

    Cialis pills https://jocialisrl.com/ cialis reviews

  25. October 18th, 2020 at 02:54 | #27

    workerаё°аё’s lam cost of cialis generic Rsnppy jfieii

  26. October 18th, 2020 at 16:53 | #28

    a maximum chance or are unknowing any outward of mi. cialis dosage med that is a extraordinary expectation or an infusion-manic therapy.

  27. October 20th, 2020 at 20:18 | #29

    what if generic viagra doesn’t work no perscription generic viagra teva pharmaceuticals viagra generic.

  28. October 21st, 2020 at 20:39 | #30

    when does viagra go generic teva generic viagra price when will viagra go generic.

  29. October 22nd, 2020 at 19:34 | #31

    marley drug generic viagra is there a generic viagra pill what do generic viagra pills look like.

  1. September 14th, 2011 at 10:33 | #1

Time limit is exhausted. Please reload the CAPTCHA.