PowerCLI

Expand all | Collapse all

Register VMs in a datastore in the vCenter inventory

nicholas1982

nicholas1982Sep 27, 2012 02:57 PM

  • 1.  Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 02:03 AM

    Hi to all the scripting guru's out there,

    I'm putting together a DR solution for our VM's, we are currently using the IBM Storwize V7000 with Remote Copy to replicate some Datastores.

    Now I have done some extensive testing and found that when you perform a switch from PROD to DR there is a a bit of a process to get the VM's up and running.

    1. I have to do a full rescan of the HBAs. Under storage adapters you can see the assigned storage devices as mounted, however you still need to go to Storage and go the the "Add Storage" wizard to readd the Datastore with the option resignaturing the volume. So this part isn't so painful except it appends a different naming convention to the datastore name, example a datastore named prd_lun100 gets named snap-5a18365a-prd_lun100 so I have to rename the datastore back to the default.

    2. I have to go through the datastores and add every virtual machine into inventory which is very tedious, and the very part I need to automate.

    I tried this one liner, which I found here -> http://www.wooditwork.com/2011/08/11/adding-vmx-files-to-vcenter-inventory-with-powercli-gets-even-easier/

    New-VM -VMFilePath "[prd_lun100] SERVER01/SERVER01.vmx" -VMHost "VMHost01.local"

    If possible I would like to expand on this, in the following ways:

    1. Automate adding the datastores with the correct naming convention, by using either the naa identifier of the LUN or LUN ID#, possibly pull this info from a CSV list.

    2. Add VM as per the one liner above but from a CSV list of some sort, however add is to a DRS Cluster rather ESXi Host, if possible prioritize adding VMs by some sort of groups flag in the CSV.

    3. Power on VMs based on a priority.

    I would really really appreciate if some one can help with this, I know probably a big ask, but scripting is not my forte and wouldn't know where to start.



  • 2.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 04:24 AM

    OK so I test this which works well, but if someone can help with modifying it so it pulls the VMX info from a list would suite me better

    $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 $Folder -RunAsync
       }
    }


  • 3.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 12:48 PM

    What exactly do you mean by pulling the VMX info from a list ?

    Do you want to provide a list of VM names and only register the corresponding VMX files ?

    Note that this will only work if the DisplayName in the VMX is the same as the filename of the VMX file.



  • 4.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 12:56 PM

    Hi Luc,

    Thanks for your reponse, yes was thinking a list like

    List

    [V7K_LUN60] SRV102/SRV102.vmx

    [V7K_LUN60] SRV103/SRV103.vmx
    However I have been playing arround with search datastore and add VM to inventory, and it seems to work wel, I guess i wanted to take a little more control of what I was adding. In addition I need a way of scripting/automating the powering on of the VM's based on a priority, not to mention answer that question "I moved it"
    I found a two liner that can power on VM's in a folder and answer that question but as you can see its not perfect.
    Get-VM -Location (Get-Folder -Name "DR_Folder") | Start-VM -RunAsync
    Get-VMQuestion | Set-VMQuestion -Option "I moved it" -Confirm:$false


  • 5.  RE: Register VMs in a datastore in the vCenter inventory
    Best Answer

    Posted Sep 26, 2012 01:16 PM

    That shouldn't be too difficult.

    Read the filenames from a CSV file and then check for each VMX file you find if it is in the list.

    Something like this

    $targetVMX = Import-Csv C:\vmxnames.csv -UseCulture
    
    $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) {      if($targetVMX -contains $VMXFile){       New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $Folder -RunAsync
        }    } }


  • 6.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 01:25 PM

    Thanks Luc,

    Would posible to have the VMs power on in the same script or would have to have 2 script and run it after this one completes?

    I need to be able to power on and answer the question about keeping the UUID



  • 7.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 01:27 PM

    If you remove the RunAsync parameter on the New-VM cmdlet, you should be able to insert your 2 lines to start and asnwer in the same block.



  • 8.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 01:36 PM

    Thanks Luc, I will gave that a try.

    Sorry just one more dumb question, I tried the CSV list modified script but it didnt work, its possible the CSV is formatted in the correct way, do mind explaining how should be?



  • 9.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 01:44 PM

    The blank in the VMX filename probably causes a problem.

    Use the Get-Content cmdlet instead, like this

    $targetVMX = Get-Content C:\vmxnames.csv

    The rest of the script should stay the same



  • 10.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 01:51 PM

    Thanks again, I will give that a try :smileyhappy:



  • 11.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 02:31 PM

    Hi Luc,

    I must not be creating the CSV list correctly, it doesn't do anything. On the other hand the other script which adds all vms from specified datastores works well, I have even appended the start-vm and answer question as you suggested. but some reason i get some errors in the task list, it does work but wondering if the script requires some tweaks, please see screenshot. I have attached both scripts as well.



  • 12.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 03:43 PM

    Could it be that some of these VMs are already powered on ?

    That's what the error seems to suggest.



  • 13.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 09:04 PM

    Hi Luc,

    No I'm testing it on 5 vms, each time it test it I power them off and remove it from inventory.



  • 14.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 09:35 PM

    Are the Tasks in the screenshot from 1 run of the script ?

    I see the same VM being powered on multiple times.



  • 15.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 26, 2012 10:04 PM

    Hi Luc,

    Yes I just run the script once, it appears to be trying to start a vm that is already in the process of powering on.

    Sent from my iPhone



  • 16.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 07:19 AM

    Hi Luc,

    I removed the -RunAsync on line 20 and the errors in the tasks don't appear anymore but now i get heaps of errors showing up on CLI, however it does all work fine, I have attached the output of the CLI, you may know exactly what it is causing it.



  • 17.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 07:39 AM

    There seem to be several errors that appear.

    • one VM already seems to be registered. You could test if the VM already exists before trying to register the VMX file
    • The poweron seems to happen before the question was answered in some cases. Could it be that the order of the Start-VM and the Set-VMQuestion cmdlets is incorrect ?
    • You try to poweron some VMs that are apparently already powered on. You could check the powersate of the VM before you do a Start-VM

    Is the script you are using the one you included in a previous post ?

    Otherwise attach the latest version.



  • 18.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 08:21 AM

    Hi Luc,

    I actually power off and unregister all the vm's NSTESTPC, SRV100, SRV101, SRV102, SRV103 prior to running the script. I even browse the datastore move those VM's into another directory, to simulate the question. I have attached the script in this post.

    What I thisk would be good is registering and powering on VMs based on a list, that way I can group the powering on of VM based on priority, im not sure if that would be easier. i just don't understand why it work but shows errors.



  • 19.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 09:06 AM

    You were retrieving all the VMs in that folder, not just the VM you just registered.

    Try it like this (I made some other changes as well)

    $Cluster = "V7000 Cluster" 
    $Datastores
    = get-datastore snap*$DatastoreNames*
    $VMFolder = "DR_Folder"
    $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) {       $vm = New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder
         
    if($vm.PowerState -ne "PoweredOn"){         $vm = Start-VM -VM $vm
          }      
    while($vm.PowerState -ne "PoweredOn"){         sleep 5
           
    $vm = Get-VM $vm.Name
          }      
    Get-VMQuestion -VM $vm | Set-VMQuestion -Option "I moved it" -Confirm:$false
       } } }


  • 20.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 11:58 AM

    Hi Luc,

    Thanks for your time with this, I wish there were some way I could repay you??

    Anyway the last script doesn't run, I get the following error. Also just to clarify does $VMFolder specify what folder in the inventory to add the VM to?

    PowerCLI C:\scripts> .\poor-man-SRM.ps1

    Invalid assignment expression. The left hand side of an assignment operator nee
    ds to be something that can be assigned to like a variable or a property.
    At C:\scripts\poor-man-SRM.ps1:4 char:12
    + $VMFolder = <<<<  "DR_Folder"
        + CategoryInfo          : ParserError: (:) [], ParseException
        + FullyQualifiedErrorId : InvalidLeftHandSide


  • 21.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 12:18 PM

    That was a copy/paste error.

    It's corrected now. Please try again.



  • 22.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 12:32 PM

    Still no luck, I get the follwing errors

    Get-VM : Cannot validate argument on parameter 'Name'. The argument is null or
    empty. Supply an argument that is not null or empty and then try the command ag
    ain.
    At C:\scripts\poor-man-SRM.ps1:24 char:21
    +         $vm = Get-VM <<<<  $vm.Name
        + CategoryInfo          : InvalidData: (:) [Get-VM], ParameterBindingValid
       ationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutom
       ation.ViCore.Cmdlets.Commands.GetVM
    Get-VM : Cannot validate argument on parameter 'Name'. The argument is null or
    empty. Supply an argument that is not null or empty and then try the command ag
    ain.
    At C:\scripts\poor-man-SRM.ps1:24 char:21
    +         $vm = Get-VM <<<<  $vm.Name
        + CategoryInfo          : InvalidData: (:) [Get-VM], ParameterBindingValid
       ationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutom
       ation.ViCore.Cmdlets.Commands.GetVM
    Get-VM : Cannot validate argument on parameter 'Name'. The argument is null or
    empty. Supply an argument that is not null or empty and then try the command ag
    ain.
    At C:\scripts\poor-man-SRM.ps1:24 char:21
    +         $vm = Get-VM <<<<  $vm.Name
        + CategoryInfo          : InvalidData: (:) [Get-VM], ParameterBindingValid
       ationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutom
       ation.ViCore.Cmdlets.Commands.GetVM
    Get-VM : Cannot validate argument on parameter 'Name'. The argument is null or
    empty. Supply an argument that is not null or empty and then try the command ag
    ain.
    At C:\scripts\poor-man-SRM.ps1:24 char:21


  • 23.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 01:37 PM

    Strange, the $vm varaiable should hold the VM that was registered with the New-VM cmdlet.

    Does this mean that one of the entries did not get registered ?



  • 24.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 01:43 PM

    Hi Luc, none of the five VMs got registered.

    Not sure if this matters but i'm running the latest powercli, vcenter 5.1 but the host is ESXi 5.0 ?



  • 25.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 01:52 PM

    No, that can't be it, that version is supported.

    And I just tested with PowerCLI 5.1 in a vSphere 5.0 environment and the registration works.

    Are there any indications in the vCenter Tasks and Events about the failing registration ?

    Do you have a debugger, like for example PowerGUI, that would allow you to run step by step through the script ?



  • 26.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 01:58 PM

    Hi Luc, I've not used PowerGUI before, I will look it up now, thanks again for you help, really appreciate it.

    BTW, have you co-written a book that could help me understand this a bit better?



  • 27.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 02:07 PM

    The PowerCLI Reference covers how you can manage all aspect of your vSphere environment .

    It is not an introduction from scratch to PowerShell nor PowerCLI.

    Have a look at my My PS library post, that gives an overview of learning resources.



  • 28.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 02:25 PM

    Hi Luc,

    I have PowerGUI running and i was able to execute the old script which worked with errors, The new one output the same errors, what info can i obtain from PowerGUI that can help find out the issue?



  • 29.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 02:57 PM

    Hi Luc,

    Not sure if this will help



  • 30.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 27, 2012 04:03 PM

    You should set a breakpoint after the New-VM and then see what is in the variables $vmxfile and $vm.

    If $vm is empty, it means that the registration didn't work, and from the $vmxfile you should see for which VMX file.

    Then you need to find out why the New-VM didn't work.

    Is the VMX already registered ?



  • 31.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 28, 2012 01:29 AM

    Hi Luc,

    My apologies i'm not entirely sure what your last post is. When I hover my mouse curer over $VMXFile it displays [snap-60fd330e-snap-vdisk_prd_100] SRV103/SRV103.vmx]

    When i hover over $vm it displays null

    In regards to your question is the VMX registered i'm assuming you mean added to vcenter inventory, if that's so then the answer is no.

    The other this is can we remove the VMFolder, and just have the vm's placed in the cluster with no Folder?



  • 32.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Sep 28, 2012 05:18 AM

    Was that on a breakpoint after the New-VM cmdlet ?

    If yes, the fact $vm is empty, shows that the registration didn't work.

    You'll have to find out why it didn't work. Could be many reasons; the VM is already registered, the filepath is incorrect, the VMX file is corrupt....

    When you hit the breakpoint, you can execute commands from the commandline, so you could try the New-VM line and perhaps you'll get some messages indicatin what goes wrong.

    And yes, you can leave out the folder, the VM will be registered in the root in that case.



  • 33.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 12:19 AM

    Hi Luc,

    My apologies, I think some of this stuff is way over my head. I wasn't quite sure what you meant by a breakpoint, so I looked it up and found this

    Get-breakpoint | remove-breakpoint
    
    Now i'm not sure if I should be placing this after New-VM as you suggested, can you please clarify?
    
    
    
    
    
    
    
    
    


  • 34.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 04:59 AM

    No, I was not referring to the builtin debugging cmdlets, but to the possibility to debug your script from the PowerGUI interface.

    See the Debugging scripts section on the PowerGUI wiki.



  • 35.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 12:59 PM

    Hi Luc,

    So I applied the breakpoint, it seemed to highlight all of line 18, anyway the $vm is still empty and the $vmxfile shows only one VM [snap-V7K_LUN60] Test/Test.vmx which is strange because that test.vmx is already registered but as Test-VC (my test VC server)

    I have attached a screenshot, not if you can maje anything of it, perhaps that test.vmx is the culprit?? Again thanks for your time.



  • 36.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 01:17 PM

    I think I understand what is happening.

    The script looks for all VMX files on the datastore, even the VMX files for the VMs that are already registered.

    The registration of a VM that is already registered will cause an error and no object is returned.

    Hence the $vm variable is empty.

    As a solution to this, we can suppress the error and add an additional test which checks if $vm is empty.

    Something like this

    $Cluster = "V7000 Cluster" 
    $Datastores = get-datastore snap*$DatastoreNames * 
    $VMFolder = "DR_Folder" 
    $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) {     $vm = New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -ErrorAction SilentlyContinue
        if($vm){       if($vm.PowerState -ne "PoweredOn"){         $vm = Start-VM -VM $vm
          }       while($vm.PowerState -ne "PoweredOn"){         sleep 5
            $vm = Get-VM $vm.Name
          }      
    Get-VMQuestion -VM $vm | Set-VMQuestion -Option "I moved it" -Confirm:$false
        }   } }


  • 37.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 01:26 PM

    Ok so I ran your last modificiation and its having the same issue answering the question, and haning on the first poweron.



  • 38.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 01:30 PM

    There was a copy/paste problem on the poweron block, I just corrected it.

    Can you try again ?



  • 39.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 01:44 PM

    Hi Luc,

    Still hanging on first VM, before you sent your correction, i decided to remove the a few lines from 23 to 25, that seem to resolve the issue, but i think i might be missing a few things even though it workd. I have yet tried the script with the second datastore starting with snap.

    Also i keep getting a parsing error line 32 char:2 unexpected "}" in expression, i just remove it seems to work then.

    So really its kind of working just trying to get past that hanging on answering the question.



  • 40.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 01:52 PM

    That line 32 can be removed, that was another copy/paste problem.

    Line 23-26 can indeed be removed if the question is there immediatly after the poweron.

    In fact lines 23-26 would loop forever since the poweron will wait for an answer to the question.



  • 41.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 02:00 PM

    OK so I actually remove the 4 lines

          }
          while($vm.PowerState -ne "PoweredOn"){
            sleep 5
            $vm = Get-VM $vm.Name
    which allows it to answers the question and proceed witht the registration of the next VM's. Also i renamed that datastore and that change you made before with silently continue seems to have done the trick.
    I only get this error now in the console
    Start-VM : 10/2/2012 11:54:06 PM    Start-VM        This VM has questions that must be answered before the operation ca
    n continue.   
    At C:\scripts\poor-man-SRM-V4.ps1:21 char:23
    +         $vm = Start-VM <<<<  -VM $vm
        + CategoryInfo          : InvalidOperation: (:) [Start-VM], VmBlockedByQuestionException
        + FullyQualifiedErrorId : Client20_VmServiceImpl_WrapInVMQuestionWatchingTask_HasQuestions,VMware.VimAutomation.Vi
       Core.Cmdlets.Commands.StartVM


  • 42.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 02:08 PM

    I ment these lines

          while($vm.PowerState -ne "PoweredOn"){
            sleep 5
            $vm = Get-VM $vm.Name
          }

    Perhaps you can do the Get-VMQuestion before the Start-VM ?
    If it comes back empty just continue with the poweron, otherwise answer the question.


  • 43.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 02:17 PM

    I will give that a try, one other thing that doesn't seem to affect the the functionality is this pops up

    Would you have any idea as to why?



  • 44.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 04:26 PM

    Yes, that message appears when you are trying to register a VMX for a VM that is already registered.

    With the ErrorAction parameter we suppress the error in the script, but it will of course be captured by the vCenter in it's events.



  • 45.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 03, 2012 12:04 AM

    Hi Luc,

    The error doesn't really bother, as it all work just fine, the only thing is the VMX /VMs have not been registered, as I remove them all from inventory prior to testing the script, so that's really strange.



  • 46.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 03, 2012 12:35 AM

    Luc,

    Although it seems to work I get these errors and for the life of me I can't see what is wrong, I have also attached the latest version of the script.

    Start-VM : 10/3/2012 10:30:12 AM    Start-VM        This VM has questions that must be answered before the operation can continue.   
    At C:\scripts\poor-man-SRM-V6.ps1:21 char:23
    +         $vm = Start-VM <<<<  -VM $vm
        + CategoryInfo          : InvalidOperation: (:) [Start-VM], VmBlockedByQuestionException
        + FullyQualifiedErrorId : Client20_VmServiceImpl_WrapInVMQuestionWatchingTask_HasQuestions,VMware.VimAutomation.ViCore.Cmdlets.Commands.StartVM
    Start-VM : 10/3/2012 10:30:42 AM    Start-VM        This VM has questions that must be answered before the operation can continue.   
    At C:\scripts\poor-man-SRM-V6.ps1:21 char:23
    +         $vm = Start-VM <<<<  -VM $vm
        + CategoryInfo          : InvalidOperation: (:) [Start-VM], VmBlockedByQuestionException
        + FullyQualifiedErrorId : Client20_VmServiceImpl_WrapInVMQuestionWatchingTask_HasQuestions,VMware.VimAutomation.ViCore.Cmdlets.Commands.StartVM
    Start-VM : 10/3/2012 10:31:02 AM    Start-VM        This VM has questions that must be answered before the operation can continue.   
    At C:\scripts\poor-man-SRM-V6.ps1:21 char:23
    +         $vm = Start-VM <<<<  -VM $vm
        + CategoryInfo          : InvalidOperation: (:) [Start-VM], VmBlockedByQuestionException
        + FullyQualifiedErrorId : Client20_VmServiceImpl_WrapInVMQuestionWatchingTask_HasQuestions,VMware.VimAutomation.ViCore.Cmdlets.Commands.StartVM
    Start-VM : 10/3/2012 10:31:22 AM    Start-VM        This VM has questions that must be answered before the operation can continue.   
    At C:\scripts\poor-man-SRM-V6.ps1:21 char:23
    +         $vm = Start-VM <<<<  -VM $vm
        + CategoryInfo          : InvalidOperation: (:) [Start-VM], VmBlockedByQuestionException
        + FullyQualifiedErrorId : Client20_VmServiceImpl_WrapInVMQuestionWatchingTask_HasQuestions,VMware.VimAutomation.ViCore.Cmdlets.Commands.StartVM
    Start-VM : 10/3/2012 10:31:43 AM    Start-VM        This VM has questions that must be answered before the operation can continue.   
    At C:\scripts\poor-man-SRM-V6.ps1:21 char:23
    +         $vm = Start-VM <<<<  -VM $vm
        + CategoryInfo          : InvalidOperation: (:) [Start-VM], VmBlockedByQuestionException
        + FullyQualifiedErrorId : Client20_VmServiceImpl_WrapInVMQuestionWatchingTask_HasQuestions,VMware.VimAutomation.ViCore.Cmdlets.Commands.StartVM


  • 47.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 03, 2012 02:43 AM

    Hi Luc,

    OK so I got a little further with some of my issues on previous posts.

    The reason why I receive the error "The specified key, name or identifer already exists" was because my VC server was on one of the snap* volumes which of course is registered and powered on. I'm not sure if there is anything else that can be added to ignore already registered VMs, but its not really an issue.

    I was able to supress this error by adding -ErrorAction SilentlyContinue to the end of line 21, I'm not if this is what you would have done, but since its working anyway I thought it would be ok, please correct me if I'm wrong.

    $vm = Start-VM -VM $vm -ErrorAction SilentlyContinue

    Start-VM : 10/3/2012 10:30:12 AM    Start-VM        This VM has questions that must be answered before the operation can continue.  

    At C:\scripts\poor-man-SRM-V6.ps1:21 char:23
    +         $vm = Start-VM <<<<  -VM $vm
        + CategoryInfo          : InvalidOperation: (:) [Start-VM], VmBlockedByQuestionException
        + FullyQualifiedErrorId : Client20_VmServiceImpl_WrapInVMQuestionWatchingTask_HasQuestions,VMware.VimAutomation.ViCore.Cmdlets.Commands.StartVM
    Start-VM : 10/3/2012 10:30:42 AM    Start-VM        This VM has questions that must be answered before the operation can continue.


  • 48.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 03, 2012 05:00 AM

    Can you try to answer the question before trying to start the VM ?

    Something like this

    $Cluster = "V7000 Cluster" 
    $Datastores = get-datastore snap*$DatastoreNames* 
    $VMFolder = "DR_Folder" 
    $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) {     $vm = New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -ErrorAction SilentlyContinue
       
    if($vm){       $question = Get-VMQuestion -VM $vm
         
    if($question){         Set-VMQuestion -VMQuestion $question -Option "I moved it" -Confirm:$false            }       if($vm.PowerState -ne "PoweredOn"){         $vm = Start-VM -VM $vm -ErrorAction SilentlyContinue
          }     }   } }


  • 49.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 03, 2012 05:46 AM

    Hi Luc,

    Unfortunetely it hangs on answering the question, so basically there are 5 systems waiting to be answered.



  • 50.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 03, 2012 05:59 AM

    I'm afraid I'm lost here.

    I would need to have a look at the system to see what goes wrong and how to fix it.



  • 51.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 03, 2012 06:19 AM

    Hi Luc,

    Its ok this version attached seems to work fine No errors, I'm not sure if there is anything else done to it to improve it.

    $Cluster = "V7000 Cluster"
    $Datastores = get-datastore snap*$DatastoreNames*
    $VMFolder = "DR_Folder"
    $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) {
        $vm = New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -ErrorAction SilentlyContinue
        if($vm){
          if($vm.PowerState -ne "PoweredOn"){
            $vm = Start-VM -VM $vm -ErrorAction SilentlyContinue
          }
          Get-VMQuestion -VM $vm | Set-VMQuestion -Option "I moved it" -Confirm:$false
        }
      }}


  • 52.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 03, 2012 06:45 AM

    Luc,

    Any chance you have a simple script that can rescan HBAs and add the mirrored volumes with Resignaturing?:smileywink:

    I think that's the missing peice to my puzzle, but only if you already have one you wouldn't mind sharing, you have already so much to help and I apreciate your time.



  • 53.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 03, 2012 07:56 AM


  • 54.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 03, 2012 08:13 AM

    I did a bit of a search, never came across that one. Thanks going to test it out tonight. One question though I noticed someone in that discussion mentioned that he didn't want to resignature the lun because it need to be reversed copied back to production. Essentially that's what need, so perhaps I don't want resignature the lun, do u know much on this?

    Sent from my iPhone



  • 55.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 03, 2012 01:25 PM

    Hi Luc,

    So I checked out Enable Mount and resignature of  snap luns on vSphere discussion and unfortunetely I wasn't able to get anything working.

    Anyway I will just keep digging around I'm sure I will get there in the end. Thanks again for all your help with this script, you are truly valuable to this community :smileywink:



  • 56.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 02:10 PM

    Do you think removing $vm before the Start-VM could fix that ?

         


  • 57.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 02, 2012 01:23 PM

    Hi Luc,

    I think we are getting closer, I renamed the V7K datastore so it didn't begin with snap, so now there is only one datastore begining with snap.

    I ran the script and didn't get any errors, however the VM files were not in a moved state, therefore the question didn't pop up, the VM's started ok.

    When deregistered the VM I moved the VM files into a different DIR simulating a move the question popped up but for some reason the script didn't answer it and it hung like that on the first VM.

    OK i see you just replied to my last message, Great i will get back to you.



  • 58.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 05, 2012 02:58 AM

    Hi LucD,

    How hard would it be to apply this functionality to your register-vmx function?

    I have a requirement to register multiple vm's on multiple datastores but I only want to register vm's that are listed within a csv file. The vm display name is used in the csv file

    Cheers



  • 59.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 05, 2012 05:13 AM

    Hi nufc09,

    I'm not sure if ths is what you want but Luc explained registering VM's from a csv file on the start of this discussion.

    http://communities.vmware.com/message/2121139#2121139

    Now what would be nice is if we could provide the inventory name of our choice, for example, I would probably like the VMs registered with the current name with something like "_replica" added to it, perhaps this can even be done without the csv?

    I'm curious to know how you go with this so please let me know, if you don't mind. :smileyhappy:



  • 60.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 05, 2012 05:17 AM

    There are 2 ways to tackle this:

    1. Register the lost VMX files, compare the VM's name with the content of the CSV file. And if the VM is not in the CSV file, unregister it.
    2. Find all the unregistered VMX files, read the DisplayName, check that name with the content of the CSV file and take action accordingly.

    Needless to say I prefer method 2, a bit more work (relatively) but less intrusive on the system



  • 61.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 05, 2012 05:57 AM

    Thanks for the info Luc, just a question regarding an idea in my previous post, without using a CSV file, would it be at all possible to register VMX / VMs with a appending a word to the VMname, like SRV01_replica



  • 62.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 05, 2012 06:06 AM

    Yes, again there are several options.

    Just to name a few

    • Read the DisplayName from the VMX file, compose the new name and use that new name with Name parameter on the New-VM cmdlet you use to register the VMX
    New-VM -Name $MyNewName -VMFilePath $VMXfile
    • Register the VM, which will use the DisplayName from the VMX file. Once the VM is registered, rename it with the Set-VM cmdlet

    $vm = New-VM -VMFilePath $VMXfile

    Set-VM -VM $vm -Name $MyNewName

    Note that in both cases the foldername and the filenames that belong to the VM will still have the old name. To avoid this phenomena, you will have to perform an svMotion.



  • 63.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 05, 2012 06:54 AM

    Hi Luc,

    I think the first method would be better suited for our needs, would you mind explaining how I would use the variable $MyNewName to call the original VMX name+append custom word?



  • 64.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 05, 2012 08:39 AM

    You can copy (Copy-DatastoreItem) the VMX file to your local machine, read the VMX file (Get-Content) and scan (best with a [regex] expression for the DisplayName.

    From there it should be trivial to create the name and change the name of the VM.



  • 65.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 05, 2012 08:23 AM

    Hi LucD,

    I am interested with option 2. This is the version of your function used to register any vms that are not registered on the datastores specified which is working great!

    function Register-VMX {
    param($entityName = $null,$dsNames = $null,$template = $false)

    function Get-Usage{
      Write-Host "Parameters incorrect" -ForegroundColor red
      Write-Host "Register-VMX -entityName  -dsNames [,...]"
      Write-Host "entityName   : a cluster-, datacenter or ESX hostname"
      Write-Host "dsNames      : one or more datastorename names"
      Write-Host "template     : register guests ($false)or templates ($true) - default : $false"
    }

    if($entityName -ne $null -and $dsNames -ne $null){
      Get-Usage
      exit
    }

    if($dsNames -eq $null){
      switch((Get-Inventory -Name $entityName).GetType().Name.Replace("Wrapper","")){
       "Cluster"{
        $dsNames = Get-Cluster -Name $entityName | Get-VMHost | Get-Datastore | where {$_.Type -eq "VMFS"} | % {$_.Name}
       }
       "Datacenter"{
        $dsNames = Get-Datacenter -Name $entityName | Get-Datastore | where {$_.Type -eq "VMFS"} | % {$_.Name}
       }
       "VMHost"{
        $dsNames = Get-VMHost -Name $entityName | Get-Datastore | where {$_.Type -eq "VMFS"} | % {$_.Name}
       }
       Default{
        Get-Usage
        exit
       }
      }
    }
    $dsNames = $dsNames | Sort-Object
    $pattern = "*.vmx"
    if($template){
      $pattern = "*.vmtx"
    }

    foreach($dsName in $dsNames){
      Write-Host "Checking " -NoNewline; Write-Host -ForegroundColor red -BackgroundColor yellow $dsName
      $ds = Get-Datastore $dsName | Get-View
      $dsBrowser = Get-View $ds.Browser
      $dc = Get-View (Get-View $ds.Parent).Parent
      $tgtfolder = Get-View $dc.VmFolder
      $esx = Get-View $ds.Host[0].Key
      $pool = Get-View (Get-View $esx.Parent).ResourcePool

      $vms = @()
      foreach($vmImpl in $ds.Vm){
       $vm = Get-View $vmImpl
       write-host -Fore Magenta $vm.Name
       $vm
       $vms += $vm.Config.Files.VmPathName
      }
      $datastorepath = "[" + $ds.Summary.Name + "]"

      $searchspec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec
      $searchspec.MatchPattern = $pattern

      $taskMoRef = $dsBrowser.SearchDatastoreSubFolders_Task($datastorePath, $searchSpec)

      $task = Get-View $taskMoRef
      while ("running","queued" -contains $task.Info.State){
       $task.UpdateViewData("Info.State")
      }
      $task.UpdateViewData("Info.Result")
      foreach ($folder in $task.Info.Result){
       $found = $FALSE
       if($folder.file -ne $null){
        foreach($vmx in $vms){
         if(($folder.FolderPath + $folder.File[0].Path) -eq $vmx){
          $found = $TRUE
         }
        }
        if (-not $found){
         $vmx = $folder.FolderPath + $folder.File[0].Path
         if($template){
          $params = @($vmx,$null,$true,$null,$esx.MoRef)
         }
         else{
          $params = @($vmx,$null,$false,$pool.MoRef,$null)
         }
         $taskMoRef = $tgtfolder.GetType().GetMethod("RegisterVM_Task").Invoke($tgtfolder, $params)
         Write-Host "`t" $vmx "registered"
        }
       }
      }
      Write-Host "Done"
    }
    }

    This is where is the function is called to register the vm's on the datastores specified

    #Prompt for datastore to search for vm's to register.
    [console]::ForegroundColor="yellow"
    [string]$RegDSname = read-host "Please enter the name(s) of the datastore to scan." `
            "Note if entering multiple datastores, then seperate with a ,
            E.g. Lun1,Lun2"
    [console]::ResetColor()

    #Convert input into array if contains comma
    If ($RegDSname.Contains(","))
    {
    [system.array]$RegDSname = $RegDSname.Split(",")
    }

    #Get-datastore to validate input is real datastore
    Get-datastore $RegDSname
    $Datastores = Get-datastore $RegDSname
    write-host -Fore green "Datastore entered is : " $RegDSname

    # Register all vm's on the provided datastore using function
    # Register-VMX -dsNames "datastore1","datastore2"
    Register-VMX -dsNames $RegDSname

    Where in the function is the best place to put the compare against the csv file?

    This is the code that I am using to import the csv file

    $Import = read-host "Enter file to be used as import"
    $OutputTrim = $Import.Trim(".csv")
    Start-Transcript -path ("D:\Migration\Logs\PostMigrationSession_Log_" + $OutputTrim + "_" + $strDate + ".txt")
    Write-Host -ForegroundColor Cyan "Servers in import file:"
    [System.Array]$MigrationCSV = Import-Csv ($WorkFolder + "Imports\PostMigration\" + $Import)

    $MigrationCSV | select -unique vmName



  • 66.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 05, 2012 08:57 AM

    I think you better go for the newer version of this function if you want to implement option 2.

    See VMX Raiders Revisited for the newer version.

    The reason, this version places the newly registered VMs in the pipeline.

    So you can just extract the name from these objects, compose the new name and then use the Set-VM.

    Does this help ?



  • 67.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 05, 2012 10:24 AM

    Thanks LucD,

    I will give the new version a creack



  • 68.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 15, 2012 07:06 AM

    Hi Luc,

    Hope you are well, sorry to bother you with but I just can't seem to figure out the required syntax to append "_replica" to the end of VM name

    Any chance you can help me. The script i pasted bellow works fine, it adds the VMs then powers them on. I tried your 2nd script

    VMX Raiders Revisited but I couldn't get them VMs power on.

    $Cluster = "V7000 Cluster"
    $Datastores = get-datastore "RC*"
    $VMFolder = "DR_Folder"
    $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) {
        $vm = New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -ErrorAction SilentlyContinue
        if($vm){
          if($vm.PowerState -ne "PoweredOn"){
            $vm = Start-VM -VM $vm -ErrorAction SilentlyContinue
          }
          Get-VMQuestion -VM $vm | Set-VMQuestion -Option "I moved it" -Confirm:$false
        }
      }}


  • 69.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 15, 2012 07:11 AM

    I would try using a Set-VM cmdlet with the Name parameter after the New-VM cmdlet.

    With that Set-VM you can change the display name of a VM.



  • 70.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 15, 2012 07:43 AM

    Thanks Luc, but how would I set the same vm name with the addition of another word, in my case _replia?

    Sent from my iPhone



  • 71.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 15, 2012 07:45 AM

    Provided you have the output of New-VM in the variable $vm, you could do something like this

    $newname = $vm.Name + "_replica"

    Set-VM -VM $vm -Name $newname



  • 72.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 15, 2012 11:49 AM

    Hey Luc,

    I haven't quite figured out exatly where to inset it, but i was playing around with the cmdlets and variables, and it required the following human intervention,

    how can suppress this or anwer yes

    PowerCLI C:\scripts> set-vm -VM $vm -Name Nic02
    Confirmation
    Proceed to configure the following parameters of the virtual machine with name
    'NiC01'?
    New Name: Nic02
    [Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help
    (default is "Y"):y


  • 73.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 15, 2012 11:59 AM

    Hey Luc, nevermind with that confirmation, I think i got it :smileysilly: "-confirm:$false"



  • 74.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 15, 2012 01:27 PM

    Hey Luc,

    I'm  not having much luck, I've tried few diiferent ways, not sure where i'm going wrong.

    $Cluster = "V7000 Cluster"
    $Datastores = get-datastore "RC*"
    $VMFolder = "DR_Folder"
    $ESXHost = Get-Cluster $Cluster | Get-VMHost | select -First 1
    $newname = $vm.Name + "_replica"
    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) {
        $vm = New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -ErrorAction SilentlyContinue
       if($vm){
          if($vm.PowerState -ne "PoweredOn"){
            $vm = Start-VM -VM $vm -ErrorAction SilentlyContinue
          }
          Get-VMQuestion -VM $vm | Set-VMQuestion -Option "I moved it" -Confirm:$false
    }
      }
      Set-VM -VM $vm -Name $newname -confirm:$false
      }


  • 75.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 15, 2012 04:46 PM

    That Set-VM should come after the registration of the VMX file.

    Something like this for example

    $Cluster = "V7000 Cluster" 
    $Datastores
    = get-datastore "RC*"
    $VMFolder = "DR_Folder"
    $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) {     $vm = New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -ErrorAction SilentlyContinue
        if($vm){       $newname = $vm.Name + "_replica"
          Set-VM -VM $vm -Name $newname -confirm:$false
         
    if($vm.PowerState -ne "PoweredOn"){         $vm = Start-VM -VM $vm -ErrorAction SilentlyContinue
          }      
    Get-VMQuestion -VM $vm | Set-VMQuestion -Option "I moved it" -Confirm:$false
        }   } }


  • 76.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 15, 2012 10:55 PM

    Hi Luc,

    Your a Superstar! Thanks for your help :smileyhappy:



  • 77.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 23, 2012 12:14 AM

    Hi Luc,

    I hate to bother you with this, but I was wondering if extra thing can be added to the script attached. Basically some of these replicated servers have virtual hard disks attached which are on non-replicated SAN volumes as they are used for DB backups etc, and we don't wan't to replicate backups.

    So after the VM has been added to the DR site they wont be able to power them on becasue it can't find that missing disk, so we manully have to remove it after we add it to inventory before powering on. If you see the screenshot you will notice Hard Disk 3 is the disk not replicated, it also can't find information on the disk, it states that the provisioned size is 0MB and Maximum size is N/A.

    My question is can we use this to check if the VM has this non existent disk and if so remove it before powering on?



  • 78.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 23, 2012 11:38 AM

    Hi Luc,

    Continuing from my previous question, I think we can use something like this to find what I would call an Orphaned Virtual Hard Disk

    Get-HardDisk -VM $vm | where {$_.CapacityKB -eq 0}

    I'm now going to try and figure out removing HardDisk this from the VMX config, but just wanted your feedback if you think I'm going down the right path?



  • 79.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 23, 2012 01:17 PM

    Ok I came up with this which seems to work ok, what do you think?

    $Cluster = "V7000 Cluster"
    $Datastores = get-datastore "RC*"
    $VMFolder = "DR_Folder"
    $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
      $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) {
        $vm = New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -ErrorAction SilentlyContinue
    Get-hardDisk -VM $vm | where {$_.CapacityKB -eq 0} | Remove-HardDisk -Confirm:$false
    if($vm){
          $newname = $vm.Name + "_Copy"
          Set-VM -VM $vm -Name $newname -confirm:$false
          if($vm.PowerState -ne "PoweredOn"){
            $vm = Start-VM -VM $vm -ErrorAction SilentlyContinue
          }
          Get-VMQuestion -VM $vm | Set-VMQuestion -Option "I moved it" -Confirm:$false
        }
      }
    }


  • 80.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 23, 2012 04:10 PM

    I would just move that new line after the 'if($vm){' line, that way you don't risk getting errors when the registration of the VMX fails.



  • 81.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 23, 2012 10:28 PM

    Thanks Luc,

    Do you think this in the only, I can achieve what I'm trying to do?



  • 82.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 24, 2012 04:47 AM

    That should work, but since I don't have a similar environment I can't actually test the script.



  • 83.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 26, 2012 12:24 PM

    Hi Luc,

    Just stuck on something, I need to filter serching Datastores to a particular Datacenter. I added some code but I dont think its quite filtering properly.

    Any thoughts?

    $Cluster = "MyCluster"
    $Datastores = Get-Datastore "MIRROR*"
    $Datacenter = Get-Datacenter "MyDC"
    $VMFolder = "DR_Folder"
    $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-Datacenter -Name $Datacenter | 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
      $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) {
        $vm = New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -ErrorAction SilentlyContinue
    if($vm){
    Get-hardDisk -VM $vm | where {$_.CapacityKB -eq 0} | Remove-HardDisk -Confirm:$false
          $newname = $vm.Name + "_Copy"
          Set-VM -VM $vm -Name $newname -confirm:$false
          if($vm.PowerState -ne "PoweredOn"){
            $vm = Start-VM -VM $vm -ErrorAction SilentlyContinue
          }
          Get-VMQuestion -VM $vm | Set-VMQuestion -Option "I moved it" -Confirm:$false
        }
      }
    }


  • 84.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 26, 2012 02:10 PM

    The problem is that this will most probably return more than 1 datastore for a datacenter.

    So your $ds variables will be an array and the $ds.Browser reference will fail.

    You can try to update the foreach statemenet. Something like this

    foreach($Datastore in (Get-Datacenter MyDC | Get-Datastore "MIRROR"))


  • 85.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 26, 2012 02:31 PM

    Unfortunetely no luck.

    Get-View : Cannot validate argument on parameter 'VIObject'. The argument is nu
    ll or empty. Supply an argument that is not null or empty and then try the comm
    and again.
    At C:\newscripts\HRemoteCopy-RegisterVMX-V1.ps1:12 char:24
    +   $dsBrowser = Get-View <<<<  $ds.browser
        + CategoryInfo          : InvalidData: (:) [Get-View], ParameterBindingVal
       idationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutom
       ation.ViCore.Cmdlets.Commands.DotNetInterop.GetVIView
    You cannot call a method on a null-valued expression.
    At C:\newscripts\HRemoteCopy-RegisterVMX-V1.ps1:15 char:55
    +   $SearchResult = $dsBrowser.SearchDatastoreSubFolders <<<< ($DatastorePath,
    $SearchSpec) | where {$_.FolderPath -notmatch ".snapshot"} | %{$_.FolderPath +
    ($_.File | select Path).Path}
        + CategoryInfo          : InvalidOperation: (SearchDatastoreSubFolders:Str
       ing) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull
    New-VM : Cannot validate argument on parameter 'VMFilePath'. The argument is nu
    ll or empty. Supply an argument that is not null or empty and then try the comm
    and again.
    At C:\newscripts\HRemoteCopy-RegisterVMX-V1.ps1:19 char:29
    +     $vm = New-VM -VMFilePath <<<<  $VMXFile -VMHost $ESXHost -Location $VMFol
    der -ErrorAction SilentlyContinue
        + CategoryInfo          : InvalidData: (:) [New-VM], ParameterBindingValid
       ationException
        + FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutom
       ation.ViCore.Cmdlets.Commands.NewVM


  • 86.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 26, 2012 03:56 PM

    Can you attach the complete script ?



  • 87.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 26, 2012 10:22 PM

    Hi Luc,

    Here it is

    $Cluster = "MyCluster"
    $Datastores = Get-Datastore "MIRROR*"
    $VMFolder = "DR_Folder"
    $ESXHost = Get-Cluster $Cluster | Get-VMHost | select -First 1
      foreachforeach($Datastore in (Get-Datacenter "MyDC" | Get-Datastore "MIRROR")) {
      # 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
      $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) {
        $vm = New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -ErrorAction SilentlyContinue
    if($vm){
    Get-hardDisk -VM $vm | where {$_.CapacityKB -eq 0} | Remove-HardDisk -Confirm:$false
          $newname = $vm.Name + "_Copy"
          Set-VM -VM $vm -Name $newname -confirm:$false
          if($vm.PowerState -ne "PoweredOn"){
            $vm = Start-VM -VM $vm -ErrorAction SilentlyContinue
          }
          Get-VMQuestion -VM $vm | Set-VMQuestion -Option "I moved it" -Confirm:$false
        }
      }
    }


  • 88.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 26, 2012 10:35 PM

    Try it like this

    $Cluster = "MyCluster"
    $DatastoreName = "MIRROR*"
    $VMFolder = "DR_Folder"
    $ESXHost = Get-Cluster $Cluster | Get-VMHost | select -First 1

    foreachforeach
    ($Datastore in (Get-Datacenter "MyDC" | Get-Datastore -Name $DatastoreName) {   # Set up Search for .VMX Files in Datastore   $ds = Get-View $Datastore.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   $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) {     $vm = New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $VMFolder -ErrorAction SilentlyContinue
        if($vm){       Get-hardDisk -VM $vm | where {$_.CapacityKB -eq 0} | Remove-HardDisk -Confirm:$false
          $newname = $vm.Name + "_Copy"
          Set-VM -VM $vm -Name $newname -confirm:$false
          if($vm.PowerState -ne "PoweredOn"){         $vm = Start-VM -VM $vm -ErrorAction SilentlyContinue
          }       Get-VMQuestion -VM $vm | Set-VMQuestion -Option "I moved it" -Confirm:$false
        }   } }


  • 89.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 27, 2012 10:58 AM

    Hi Luc,

    That works, I just had to make a minor correction on line 6, and I also decided to add a Datacenter Name variable.

    Thanks again :smileyhappy:



  • 90.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 18, 2012 10:37 AM

    Hi LucD,

    This seems to work but I was wondering if there is a better way of doing it?

    [System.Array]$MigrationCSV = Import-Csv C:\temp\vmxnames.csv

    [system.array]$GroupedMigrationVms = $MigrationCSV | Group {$_.vmName}

    $Cluster = "MYCLUSTER"

    $Datastores = "MYDATASTORE"

    $VMFolder = "MYFOLDER"

    foreach($vm in $GroupedMigrationVms)
    {
    $targetvmx = ($vm.name +".vmx")


    $ESXHost = Get-Cluster $Cluster | Get-VMHost | select -First 1

    foreach($Datastore in Get-Datastore $Datastores) {

                    # Collect .vmx paths of registered VMs on the datastore

                    $registered = @{}

                     Get-VM -Datastore $Datastore | %{$_.Extensiondata.LayoutEx.File | where  {$_.Name -like "*.vmx"} | %{$registered.Add($_.Name,$true)}}
                    # write-host $registered

       # Set up Search for .VMX Files in Datastore

                    New-PSDrive -Name TgtDS -Location $Datastore -PSProvider VimDatastore -Root '\' | Out-Null

                    $unregistered = @(Get-ChildItem -Path TgtDS: -Recurse | `

                                     where {$_.FolderPath -notmatch ".snapshot" -and $_.Name -like  "$targetvmx" -and !$registered.ContainsKey($_.Name)})
                 #    write-host $unregistered
                     Remove-PSDrive -Name TgtDS

       #Register all .vmx Files as VMs on the datastore

       foreach($VMXFile in $unregistered) {

                      New-VM -VMFilePath $VMXFile.DatastoreFullPath -VMHost $ESXHost -RunAsync

       }
       }
    }



  • 91.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 18, 2012 10:45 AM

    That should work at first sight.

    I don't immediatly see how you could do this in a better way.



  • 92.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 19, 2012 04:43 AM

    Hi LucD

    I did find an issue with the script…This will work if I want to match a name in the csv to the vmx file name on the datastore, not the vm display name within the vmx file. Is there a way to extract the vmx display name from the vmx file without registering the vm first?



  • 93.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Oct 19, 2012 05:36 AM

    That is correct, the Display Name in a VMX file can be different from the name of the VMX file.

    You can of course retrieve the VMX file with the Copy-DatastoreItem cmdlet or via a regular Get-Item when you use a datastore PSDrive, and then read the local copy of the VMX file and extract thde Display Name (if present).



  • 94.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Nov 08, 2018 12:24 PM

    Hi LucD,

    I came a cross this great script, so i was wondering how my csv file would look like

    Here's what I did I don't know if it's correct



  • 95.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Nov 08, 2018 02:09 PM

    The script doesn't need a CSV file as input.
    You only need to provide one or more datastores.
    Unless you are referring to another script (not the last one in this thread)?



  • 96.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Nov 08, 2018 02:59 PM

    I'm referring to this script below but mostly the Register all .vmx part with an input

    $targetVMX = Import-Csv C:\vmxnames.csv -UseCulture

    $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) {
        
    if($targetVMX -contains $VMXFile){
         
    New-VM -VMFilePath $VMXFile -VMHost $ESXHost -Location $Folder -RunAsync
        }
       }



  • 97.  RE: Register VMs in a datastore in the vCenter inventory

    Posted Nov 08, 2018 03:32 PM

    If you have the orphaned VMX files already in a CSV, you can just run the New-VM on each entry.
    But note that you also need an ESXi node to register the VM.

    You could put that in the CSV as well, or you could register all entries on a fixed, hardcoded ESXi node.

    Note that the VMX path needs to be in the correct format.

    See example 11 on the NewVM cmdlet's online help page.

    Something like this

    # CSV file layout

    # 'Path'

    # '[DS1] VM1/VM1.vmx'

    # '[DS2] VM2/VM2.vmx'

    #

    $vmxs = Import-Csv -Path vmxpaths.csv -UseCulture

    $esx = Get-VMHost -Name MyEsx

    foreach ($vmx in $vmxs) {

      New-VM -VMFilePath $vmx.Path -VMHost $esx -RunAsync

    }