VM Variable for the virtual computer object

Hello

I am connected to multiple vcenters where we have a few VM objects that have the same name (no duplicates in the vcenter even).

and I need to run a vm - get when you are connected to the 2 vcenters and store that in a variable $vms

It is always the case for virtual machines with the same name that if a virtual machine is running in a vcenter, it is turned off in the other vcenter. (DR)

for virtual machines in this case, I need my variable to store the computer object virtual that is powered AND ignores the engine off... for other virtual machines, I need to power on and power off power vms to be included.

Here's what I do, but it doesn't work

$vms = (get - vm |) {ForEach-Object

If ($_.name - eq $null) {}

$_ = ($_ |  (Where-Object {$_.powerstate-eq "réceptrices"})} else {$_}

})

Hello, max2001-

How about something like the following:

## get all VMs from all connect vCenters, and group them by name$arrAllVMs_grouped = Get-VM | Group-Object Name

$arrDesiredVMs = @()## for any group of VMs where there is more than one (2, presumably), only return the PoweredOn VM in the group$arrDesiredVMs = $arrAllVMs_grouped | ?{$_.Count -gt 1} | %{$_.Group | ?{$_.PowerState -eq "PoweredOn"}}## and for the groups of VMs where there is only one VM in the group, add that VM to the DesiredVMs array$arrDesiredVMs += $arrAllVMs_grouped | ?{$_.Count -eq 1} | %{$_.Group}

Who will be:

  1. get all virtual machines and group by name
  2. groups of virtual machines where there is more than one, just take those who are in the PowerState PoweredOn
  3. and, grab all the VMS are groups of count 1 (named unique VMs), without regard to their PowerState

What to do for you?

Tags: VMware

Similar Questions

  • After the Virtual Machine is hot migrated lose the reference to the virtual computer object (VMware.Vim.VirtualMachine)

    Hello

    In my VB.Net application, I retrieve the virtual computer object (VMware.Vim.VirtualMachine) through scripting Powershell VI.

    If the Virtual Machine is migrated to another host (hotmigrate) I receive an event (VMware.Vim.VmMigratedEvent), which also holds the moref of the Virtual Machine. I tried to use the updateview method to refresh the virtual computer object but failed with an error message stating that the object could not be found, or never existed.

    I also tried to recover the virtual computer object again, throug the method Client.GetView and the moref returned by the event, but the same error message.

    How can I get my hands on the virtual computer object or update after migration to another host takes place. I have to get it back again? It would be great if I could do it somhow with information from moref I hold the event!

    Any help is appreciated!

    Concerning

    Manfred

    Sorry, but I can only show you how to do this in PowerShell.

    I use the purpose of the task to get to the prompt MoRef.

    Here's how:

    $vmName = 
    $tgtHost = 
    $tgtPool = 
    
    $vm = Get-VM $vmName | Get-View
    $poolMoRef = (Get-ResourcePool $tgtPool | Get-View).MoRef
    $esxMoRef = (Get-VMHost $tgtHost | Get-View).MoRef
    
    $task= Get-View ($vm.MigrateVM_Task($poolMoRef, $esxMoRef, "lowPriority", "poweredOn"))
    
    while($task.Info.State -eq "running" -or $task.Info.State -eq "queuing"){
      $task.UpdateViewData()
    }
    
    $vmImpl = Get-VIObjectByVIView -MORef $task.Info.Entity
    

    I don't know how you get at the VmMigratedEvent event, but the MoRef in there is pointing to the correct prompt.

    In the following script, I extracted all the events related to the task of vMigrate immediately after the vMigrate task finished

    function Print-VmName{
         param($event)
    
         $MoRef = New-Object VMware.Vim.ManagedObjectReference
         $MoRef.Type = $event.vm.vm.type
         $MoRef.Value = $event.vm.vm.Value
         $vm = Get-View $MoRef
         Write-Host $vm.Name
    }
    
    $events = Get-VIEvent -Start (Get-Date).addminutes(-15)
    $events | % {
         $event = $_
         $eventType = $_.GetType().Name
         switch ($eventType){
              "VmMigratedEvent" {
                   $eventType
                   Print-VmName $event
              }
              "VmEmigratingEvent"{
                   $eventType
                   Print-VmName $event
              }
              "VmBeingHotMigratedEvent" {
                   $eventType
                   Print-VmName $event
              }
              "TaskEvent" {
                   $eventType
                   Print-VmName $event
              }
         }
    }
    
  • How to create an additional column for the description of the virtual computer object?

    Hi all

    I would like to know if it is possible to add a column more in the description of VMware vsphere, for the moment we have column / field called 'Notes' in which we can add our comments on a particular virtual machine / items.

    I wanted to add a column called the backup status, is it possible to add it to the database of the VM? which can be edited client VSphere.

    Any ideas would be greatly appreciated.

    Thank you

    AWT

    You can add fields for virtual machines.

    Click on a virtual machine.

    Then, go to the menu Manager

    Choose custom attributes.

    André

  • Change the settings for the virtual computer video card

    After upgrade of several virtual machines to the latest version of material, some of our virtual machines experienced a problem where the 3D has been activated and automatic detection has been updated with the manual. Some side effects have been experienced. I am now seeking to create a workflow to disable 3D and set to automatic detection for our servers. I found the properties "enable3DSupport" and "useAutoDetect" under VirtualDeviceConfigSpec.VirtualDevice.VirtualMachineVideoCard.

    I had planned this script in action and create a workflow to move a virtual machine as the user selects.

    I fired up Onyx and pulled the following information:

    // ------- ReconfigVM_Task -------
     
    var spec = new VcVirtualMachineConfigSpec();
    spec.changeVersion = "2013-02-21T16:34:32.130873Z";
    spec.deviceChange = System.getModule("com.vmware.onyx").array(VcVirtualDeviceConfigSpec, 1);
    spec.deviceChange[0] = new VcVirtualDeviceConfigSpec();
    spec.deviceChange[0].operation = VcVirtualDeviceConfigSpecOperation.edit;
    spec.deviceChange[0].device = new VcVirtualMachineVideoCard();
    spec.deviceChange[0].device.key = 500;
    spec.deviceChange[0].device.deviceInfo = new VcDescription();
    spec.deviceChange[0].device.deviceInfo.label = "Video card ";
    spec.deviceChange[0].device.deviceInfo.summary = "Video card";
    spec.deviceChange[0].device.controllerKey = 100;
    spec.deviceChange[0].device.unitNumber = 0;
    spec.deviceChange[0].device.videoRamSizeInKB = 8192;
    spec.deviceChange[0].device.numDisplays = 1;
    spec.deviceChange[0].device.useAutoDetect = true;
    spec.deviceChange[0].device.enable3DSupport = false;
     
    managedObject.reconfigVM_Task(spec);  // VirtualMachine
    
    
    

    I know that most of that is not necessary, but I have tried two different ways and received the following error:

    Cannot convert com.vmware.vim.vi4.VirtualDeviceConfigSpec@1 in [com.vmware.vim.vi4.VirtualDeviceConfigSpec] (name of the dynamic Script Module: changeVideoCard3DEnable #9)

    Can someone provide some guidance? It seems that most actions and workflows in vCO seek information in the environment rather than change things.

    Thank you

    -Zach

    Morning,

    untested but try this way:

    spec var = new VcVirtualMachineConfigSpec();
    
    
    var myDeviceChange = new Array();
    
    
    var myVirtualMachineVideoCard = new VcVirtualMachineVideoCard();
    
    
    Context of var = new VcVirtualDeviceConfigSpec();
    
    
    
    
    myVirtualMachineVideoCard.useAutoDetect = true;
    
    
    myVirtualMachineVideoCard.enable3DSupport = false;
    
    
    
    
    configSpec.operation = VcVirtualDeviceConfigSpecOperation.edit;
    
    
    configSpec.device = myVirtualMachineVideoCard;
    
    
    
    
    myDeviceChange.push (configSpec);
    
    
    spec.deviceChange = myDeviceChange;
    
    
    
    
    vm.reconfigVM_Task (spec);

    But it's untetested.

    Concerning

  • Performance for the virtual computer table appears in Vcenter server.


    Hi people,
    The array of performance for ESXi and virtual computers is not displayed in the server Vcenter Server 4.1 after clicking on the help of Tab.Any seen on this will be appreciated. Please find the screenshot.

    Thank you
    vmguy

    That the said KB - No.

    Maish

  • Determine the maximum use of the processor for a virtual computer in the custom user interface

    I want to determine the maximum use of the processor for a virtual computer in the custom user interface.  How can I do this?

    If I use a supermetric, there is no kind of attribute under CPU called "maximum use.

    Certainly, you get points for a long question! Although to be fair, it's probably my fault to feed you so much information to digest at once.

    1. I would say you can do two ways visually. Use the operations > detail view for 'normal ranges' use the upper limit of the normal range as your typical max. You want an absolute peak, add the metric of a graph or observe that highlight high and low watermarks.

    2. There are a lot of ways to display data, but if you want to display a single metric over a period of time, we could use the following widgets [on top of my head]:

    Top - N analysis

    Weather map

    Analysis of distribution of data

    Among these, I think of your desire for a "peak". Who you want real value, which eliminates the weather map. Then, I think that the concept of a 'Summit' and what is the best thing, I think that the 95th percentile... then I came with the widget of data distribution. The decision is ultimately yours given your particular use case.

    3. you can have it apply to several virtual machines - it's just a widget capable of being an independent provider or receiving widget (metrics, DO NOT choose to select resources). Each resource/metric will add to the widget and you can remove them if you like after it is added. You can certainly all the time you visit... It is date and time standard options you have in all the other widgets chart. With the widget data distribution, you want as much time as possible to get an accurate histogram of the cycles of workload.

    4. This is similar to the question above. You can certainly add parameters of individual resource or a DM that summarizes or AVG groups of resources. And as above, the delay is configurable, along with the other graph widgets.

    5. it's part of Q4 - you can sumN or avgN up to any number of resources with a SM, then discovers that SM in the widget of data distribution. When I said container, I mean an application, group resource pool... all that acts as a container parent within the vCOps.

    6. that's correct, SMs calc using data collected last points... aka single period of time. When you are referring to the longest period, I gave you a few examples of the attributes that are composed of several periods of time which are calculated and created by the adapter for VMware vCenter behvaior. In this case, you have the GVA 15 min CPU 1.5; These specific simple mobile GVA can be specific OR a copy using SMs. Next, you will have the chance is to find a way to distribute what you need through a widget [at that time].

    7. the distribution of data is not for export, it is for Visual functions. If you want the data in CSV, just use a typical chart of metrics and export to a csv and calc your own pics, avg, 95th, whatever.

    8. This is a bit of a mix of all your questions, put in place.

    You are right, if you added those 3 VMs, then calc was the 95th of the AVG. Like Q7, you would not export the data of the distribution of data because the raw data points are not - you do not pass the metric to a metric graphics standard and export via csv.

    Take advantage of...

  • NET application SAN LUN connection for a virtual computer on the network

    Hi guys

    I have a LUN of SAN NetApp ready for a virtual computer that is connected to the network.

    How can I make the virtual machine network?

    I created another vNic and added to it as a secondary virtual machine network, but is there a better way to do this?

    Should I be using the VMKernel network and choose iScsi?

    Thanks, Julien

    Hi Julien,

    Introduce the network of the virtual machine as if it were any other network. No need to have a vmkernel, unless you want to create an iSCSI data store.

    Set up your network inside the virtual machine with an IP address in the same subnet as your storage space. Try to ping of your storage space for the guest. Configure your iSCSI initiator and present your logic unit number on the virtual computer in your NetApp.

    Concerning

    Franck

  • How to change the IP address for the virtual using Vsphere Client computer?

    Hello

    I have Esxi 5.0.0 and using the client vsphere 5.0.0 and deployed a VM with Centos 5.6.

    Can I change Ipadress assigned to the virtual computer that is already installed?

    Could you please let me know in detail of the measures to be executed in order to change the IP address if it is authorized using Vsphere Client 5.0.0

    You can take a look at this blog sound to change IP on the Windows virtual machine, probably using the CLI of power it should be possible on linux VM

  • Customization of the comments for the virtual machines deployed from model has stopped working

    Hi all

    (Environment: vCenter and ESXi 10 5.1 hosts running Build #3070626)

    We have a model 2012R2 and a file specification of customization that allows us to deploy the VMs 2012R2 server. It worked well for a while. After the Christmas break, it seems more work correctly and we havn't knowingly changed anything to cause this. We have fixed our ESXi hosts Build #3070626 October 6, but have deployed VMs of model since, without problem.

    We have all staged for the VM in advance (IE AD entry of objects and DNS). And then powered the deployed virtual computer, sysprep runs, but does not seem to apply settings in the customization file (IE rename the virtual computer, set the Admin password, join the domain etc.). If feed us the cycle of the VM, sysprep is running again, but even once, does nothing.

    I have attached the contents of my file guestcust.log of a computer deployed virtual (see below), but I do not see the clues about the problem. I thought initially the error on the first line was important, until I've found it is also present on the virtual machines that have been successfully deployed from this template in the past, so it's maybe a Kipper.

    Does anyone have advice for troubleshooting this?

    TIA

    Mark

    ==========

    guestcust.log

    ==========

    Could not query value reported in the registry (the system cannot find the file specified.)

    Sysprep from Windows Respecialize operating detected.

    Copy the files from C:\Windows\TEMP\vmw7DEB.tmp to C:\Windows\TEMP\vmw8A3E.tmp.

    Rescheduling of customization of the guest operating system.

    "Executing command C:\Windows\system32\schtasks.exe / create /sc ONSTART $ more HIGH/np/z v1 /ru SYSTEM /tr" C:\Windows\TEMP\vmw8A3E.tmp\guestcustutil.exe customize - sealparam \"/quiet/generalize/oobe /reboot\ ' NIC - 4000 - schedulenativeunobfusc ' /tn"VMware Guest OS task of customization.

    At the request of guest OS customization task invoked.

    Remove scheduled task of customization of the guest operating system.

    Execution of command C:\Windows\system32\schtasks.exe, /f/delete /tn "VMware Guest OS task of customization"

    Personalization current 2016 to 1 - Feb - 11 18:32:42

    RPCI: Send request = 'deployPkg.update.state 4 C:\Windows\TEMP\vmware-imc\guestcust.log 0'

    RPCI: Envoy = 'deployPkg.update.state 4 C:\Windows\TEMP\vmware-imc\guestcust.log 0' request, response = ", len = 0, status = 1

    Key successfully open SYSTEM\CurrentControlSet\Control\Session Manager\

    Size of 27 reg_multi_sz.

    Read the multi_sz registry autocheck autochk/q/v value *, size 27.

    value chain of registry autocheck autochk/q/v *.

    1 items back

    Obtained the session mgr BootExecute.

    Native App sysprepDecrypter.exe, arguments "

    Copied file sysprepDecrypter.exe to C:\Windows\system32\sysprepDecrypter.exe

    Update boot run value.

    Created / opened key \Guest Customization\ SOFTWARE\VMware, Inc. successfully.

    New shoe, run:

    autocheck autochk/q/v *.

    sysprepDecrypter.exe

    System drive: C:

    Move the folder "sysprep" to "C:".

    Select * from win32_networkadapter where manufacturer! "Microsoft" and ServiceName =! = "VMnetAdapter" and the manufacturer is not null and MACAddress is not null

    1 objects found. Pointer f049a8. return code 0(0x0)

    "" "0 items found." " Pointer to 0. return code 1(0x1)

    00:50:56:B0:70:46 the value for the property return system

    Setting dhcp for nic # 0

    Return value \\VMT-W2K12R2\ROOT\CIMV2:Win32_NetworkAdapter.DeviceID="10' for the system property

    ASSOCIATORS OF {\\VMT-W2K12R2\ROOT\CIMV2:Win32_NetworkAdapter.DeviceID="10"} where ResultClass = Win32_NetworkAdapterConfiguration

    1 objects found. Pointer eee290. return code 0(0x0)

    "" "0 items found." " Pointer to 0. return code 1(0x1)

    Clear the gateway ip addresses.

    Enabling DHCP on the computer

    Returns the value for the system property \\VMT-W2K12R2\ROOT\CIMV2:Win32_NetworkAdapterConfiguration.Index=10

    DNS server IP configuration

    Execution of command C:\windows\system32\sysprep\sysprep.exe/quiet/generalize/oobe/reboot /unattend:C:\sysprep\sysprep.xml

    Successfully executed the command C:\windows\system32\sysprep\sysprep.exe/quiet/generalize/oobe/reboot /unattend:C:\sysprep\sysprep.xml

    Try to connect network interfaces, try 1

    RPCI: Send request = 'deployPkg.update.state 4 103 C:\Windows\TEMP\vmware-imc\guestcust.log@4000'

    RPCI: Envoy = 'deployPkg.update.state 4 103 C:\Windows\TEMP\vmware-imc\guestcust.log@4000' request, response is "queryNicsSupported", len = 18, State = 1

    Got answer VMX 'queryNicsSupported '.

    RPCI: Send request = 'deployPkg.update.state 4 104 C:\Windows\TEMP\vmware-imc\guestcust.log@4000'

    RPCI: Envoy = 'deployPkg.update.state 4 104 C:\Windows\TEMP\vmware-imc\guestcust.log@4000' request, response = 'connected', len = 9, State = 1

    Got VMX response "connected."

    Network interfaces are connected to 0 seconds

    =============================================

    OK, I myself fixed the end.

    I created a new customization file with exactly the same settings as the old file, and it worked. I can only assume that the old customization file has been altered somehow.

  • SRM 5.5 - vSphere replication - error: impossible to reverse the replication for the Virtual Machine. A snapshot operation cannot be performed

    Hi all, we have just run a test DR failover of a couple of virtual machines in our protected our failover site and all site swung perfectly, two virtual machines came online and all applications work well. However when we cam to r-eprotect machines virtual, we get some errors.

    One of the virtual machines seems to have lived the reprotect end process, it is still running, but has not moved to 89% for some time. The virtual machine has a couple of grand (a little less than 2 TB) VMDK. slow progress is just a consequence of the large VMDK?

    More worrisome is the virtual machine which don't reprotect at all. It generates an error whenever I click on the "Restore" button (error: impossible to reverse the replication for the Virtual Machine.) A snapshot operation can not be performed).


    Does anyone have any ideas as to the cause?

    Thanks in advance for any help.

    Andy

    Finally got to the bottom of this. The issue was that reprotect SRM work was trying to dispel any snapshots that were taken on the computer object virtual destination in VMWare, but could not clean snapshots.

    The reason why snapshots would not consolidate was because it was snapshots of temporary VEEAM who in fact any snapshot file listed in the VSAN data store. So when we looked through the browser data store, no snapshot file existed in the virtual computers folder. Trying a manual removal also failed.

    To fix this, we created a snapshot of the virtual machine in the original data center (note is the engine to the bottom of the virtual machine), this effect was to get rid of the 'fade' snapshot that was visible in the Snapshot Manager that VEEAM backup had left behind. Once this had disappeared, the reprotect back to DCA worked perfectly.

  • Script to rename the virtual computer by name DNS listed in VC

    I am very new to powershell, and I tried to understand this by using pieces of code I found, but nothing helped.

    I'm looking for a script to take the given DNS host name for a virtual machine listed in VCenter and rename the virtual computer.

    For example.

    Host01VM01 (as shown in Vcenter) - the DNS name of the "something.xyz.com".   VM and rename it "something.xyz.com" in Vcenter.

    To run the script only for a group called "Mycluster" you can do:

    Get-Cluster "My Cluster" | Get-VM | `
    Where-Object { $_.Guest.HostName } | `
    ForEach-Object { Set-VM -VM $_ -Name $_.Guest.HostName -Confirm:$false }
    

    This script will only work for VMS that have installed VMware tools and probably only for VM which are turned on.

  • The virtual computer upgrade to v7 by Shane

    I work with a great script of Arne and spin in some questions.  Original screenplay is here and on poshcode here.  The part that I am looking is the PowerOff-VM function.  The problem that I ran was that, since it uses the VMTools status to determine if the virtual machine has been turned off or not, if the service stopped running more than a few seconds before that OS virtual machine completed its shutdown process, the virtual machine hardware upgrade fail and the poweron would fail on the vCenter Server because the VM was not done actually stop.  Meanwhile, the script would continue to wait for the virtual machine can be fed, even if she missed to vCenter, so a loop at the break for the virtual machine be brought upward indefinitely pending.

    I thought I was smart about it and just change the conditional ToolStatus PowerState-match "PoweredOff", but this condition has never recognized and therefore are never reunited, even after vCenter had completed the task, so never the kickoff of the hw upgrade or the PowerOn.

    Am I missing something that the State would never satisfied?   I inserted my variant of Arne function below:

    Any help would be greatly appreciated.

    Thank you

    @dboftlp

    Function PowerOff-VM ($vm) {}

    sleep 20

    Stop-VMGuest - VM $vm - confirm: $false | Out-Null

    {}

    $vmps = $vm. PowerState

    Write-Host $vm stop! ForegroundColor - yellow

    sleep 5

    } until ($vmps - match "PoweredOff")

    If ($vmps - match "PoweredOff") {}

    $Shutdown = 'Ok'}

    else {}

    $Shutdown = 'Not ready'}

    return $Shutdown

    }

    The problem with your version of the function PowerOff-VM, it's that the $vm variable is not updated during the shutdown process. Once you do a Get - VM and assign the object to a variable, the object in the variable remains the same. It reflects the State of the virtual machine at the point where you did Get - VM. If the State of the virtual machine changes over time, you will need to do a new VM - Get to get the new State. So if you want to follow the shutdown process, you will need to do a Get - VM in a loop. I changed your code a bit to change that. Now, it should work. However I do not test because I don't want to stop my VM ;-).

    Function PowerOff-VM($vm){
    
      sleep 20
      Shutdown-VMGuest -VM $vm -Confirm:$false | Out-Null
    
      do {
        Write-Host $vm is stopping! -ForegroundColor Yellow
    
        sleep 5
        $vmps = (Get-VM $vm.Name).PowerState
      }until($vmps -match "PoweredOff")
      if ($vmps -match "PoweredOff"){
        $Shutdown = "Ok"}
      else{
        $Shutdown = "Not Ready"
      }
      return $Shutdown
    }
    

    Best regards, Robert

  • Cannot save settings: unable to create a configuration file for the required configuration object

    When I try to open the application in the administrator account it say - could not save the settings: unable to create a configuration file for the required configuration object

    Thanks for the reply.i think that a virus changed I scan my computer and discovered C:\users\jason\AppData\local\temp\low\temporary internet files\content. IE5\TLIFXGRH\ why is Task Manager disabled people [1]

  • Reload the Configuration of the virtual computer after changing the VMX file

    Hello

    If I make changes to a file on a virtual machine's .vmx in vCenter 5.5 is automatically valid configuration for the engine power vm off? I made some changes earlier and it seemed to be the case, but one of the steps that I see in some of the documents is to reload the configuration of the vm, so it can be used appropriately. So this happens automatically or not?

    Hello

    If she turned off the virtual computer, then during power on, changes to take effect.

    Concerning

    Mohammed

  • Move-vm can migrate a powered off the virtual computer to a DRS cluster?

    When I try to move-vm has propelled off VM to a destination of DRS cluster, he says that he cannot migrate a powered off the virtual computer to a DRS cluster.   I can explicitly name the destination of the host and it works, but that defeats the purpose of using the DRS and forces me to script on the destination hosts.

    I do something wrong or I would be able to migrate a powered off the virtual computer to a DRS cluster?

    Thank you

    -MattG

    Hello, MattG-

    I get the same behavior as you when you try to move a VM PoweredOff to a DRS cluster, specifying the cluster as the value for the parameter - Destination to Move-VM (using PowerCLI v5.1 Rel 2 v5.5 Rel 1).  Not quite what I expected.

    To work around the problem, and without having to appoint a particular host as destination, you could use some Get-Random, do something like:

    Move-VM myVM0 -Destination (Get-Cluster myDestDRSCluster | Get-VMHost | ?{$_.State -eq "Connected"} | Get-Random) -RunAsync
    

    Who should receive the machine said cluster and on a host that is in the connected state.  A subsequent operation to the market (whenever do you eventually) should then see DRS power on the virtual machine on a suitable host in the cluster.

    Maybe the dev team can comment if this behavior is the expected or desired.

    Anyway, how does do for you?

Maybe you are looking for