Query average CPU of replicated VMs

As I continue to learn PowerCLI and PowerShell in general, I appreciate when there is a request for any kind of report with some values that may not come in 'canned' presentation. Few weeks ago, I was asked to schedule a report of all of the replicated VMs with their provisioned space and average CPU usage among other values. Without even looking to see if the Web Client GUI or other tools could provide this information; I wanted to use a PS One-liner, not only for my own practice but because it can be easily scheduled to run weekly or monthly.

For the basic query and filtering, I have watched enough PowerCLI videos on Pluralsight (😉) to know how to filter out certain VMs and get many of their properties. In this case, all replicated VMs reside on datastores with a common part of the name, so that was simple; but rounding the ProvisionedSpace in GB to fit nicely in Excel and listing the Average CPU usage for the last week was not, at least for me. Thankfully, we have Google and many unselfish bloggers who have shared how this type of properties can be displayed properly.

Below is the command I'm using and as always just wanted to post it here as reference for the future and in hope that someone else may find it useful.

The command will list VMs residing on datastores with "RPL" in their name; display the VM's Name, allocated CPU and RAM, ProvisionedSpaceGB rounded and Average CPU usage for the last week; this will be exported as a .CSV file.

Get-Datastore RPL* | Get-VM | Select Name,NumCpu,MemoryGB,@{n="Provisionedspace(GB)"; E={[math]::round($_.ProvisionedSpaceGB)}},@{N="CPU Usage (Average), Mhz" ; E={[Math]::Round((($_ | Get-Stat -Stat cpu.usagemhz.average -Start (Get-Date).AddDays(-7) -IntervalMins 5 | Measure-Object Value -Average).Average),2)}} | Export-Csv C:\FileName.csv -NoTypeInformation




This property rounds the Provisioned Space in GB, otherwise it will display a very long number.
@{n="Provisionedspace(GB)";E={[math]::round($_.ProvisionedSpaceGB)}}


This part averages the CPU for the last week.
@{N="CPU Usage (Average), Mhz" ; E={[Math]::Round((($_ | Get-Stat -Stat cpu.usagemhz.average -Start (Get-Date).AddDays(-7) -IntervalMins 5 | Measure-Object Value -Average).Average),2)}}



Como agregar Standard Switches y/o PortGroups con PowerCLI

Metodo para agregar Standard Switches y/o Port Groups a todos los hosts en tu cluster usando PowerCLI cuando no existe Switch Distribuido (VDS).

Cuando un Switch Distribuido (VDS) no está presente en el ambiente, bien sea por no tener licencia Enterprise Plus o por cualquier otro motivo y en vez se usan Standard Switches (VSS) en cada uno de los hosts; la configuración y nombre de tus VSS y sus Port-Groups deben ser identicas, de lo contrato sabemos que errores podrían ocurrir al intentar hacer vMotion por ejemplo.


Si es necesario agregar o editar uno o mas Virtual Standard Switches y/o Port-Groups a tus hosts, PowerCLI hará esta tarea mucho más fácil, rápida y consistente. 

En vez de agregar cada uno de los VSS y/o Port-Groups de manera manual y repetitiva atravez del GUI o incluso usando ESXCLI en cada host con sesiones SSH; puedes hacer estas configuraciones con un par de líneas en PowerCLI.



Iniciamos creando una variable de los hosts que necesitas modificar:

Bien sea incluyendo todos hosts que usan parte del nombre, con un * como wildcard:

  
Agregando uno de tus clusters completos, si es que existe mas de uno:


O listando los hosts individualmente, si por algun motivo esto fuera necesario:

  

Si el VSS no existe y debes agregarlo, puedes usar el siguiente syntax para crearlo en todos los hosts contenidos en tu variable $Labhost:





El anterior ejemplo usa -MTU y -NumPorts para modificar estos de su defecto, pero esos parametros no son obligatorios y se pueden omitir.

Despues de crear el VSS o si ya existe y solo necesitas crear nuevos Port Groups, debes identificar el nombre del VSS donde seran agregados. En este ejemplo el resultado sera que en todos los hosts incluidos en la variable $myhosts, se creara un Port-Group llamado Replication-vlan en el switch vSwitch3 tageado con VLAN 405





Nota: Los diferentes comandos, variables y las imagines no necesariamente son relacionadas unas con otras, como puedes ver en el penultimo ejemplo para agregar un VSS el nombre de la variable y el VSS no concuerdan con los otros casos en este post. Estan ahi como demostracion y referencia.










My road to vExpert

vExpert: wow that guy works for VMware and must know it all. 

When I first started seeing and hearing the term vExpert in the different community virtualization events, podcasts, webinars and on people's Bio's on LinkedIn and Twitter, I thought it was a selective distinction for a very few, top product specialists within VMware; I believed it to be some sort of certification for its employees.
Later on, I noticed how others outside VMware also called themselves vExperts; but these individuals were known bloggers and virtualization community heavyweights; then I thought, maybe they get the privilege since they are so well versed in the technology and have proven it with their presentations, blog posts and even books. 

I didn't bother to look at the requirements for that "certification" or what it really meant, instead I just kept focused on VCP and VCAP just assuming vExpert was out of reach.

It wasn't until I started engaging more in the Boston VMUG and with the vBrownBag and LATAM crew that I realized the vExpert recognition was for the Community, for enthusiasts and evangelists of the technology. Even then, my assumption was that it would take an enormous amount of dedication, commitment and actual high technical expertise to become one.

My interest in attaining this award grew as I became aware of a key benefit: being able to use VMware products in a Home Lab; What? Have the ability to practice in your home gear without reinstalling every 60 days? Great, I needed to start putting the effort and pursue this recognition from VMware; I enjoy virtualization and this will only allow me continue learning and growing in that space. That benefit by itself is huge, the other perks are also very valuable, I'm not underestimating their value.

Found my mentors: Ariel Sanchez y Los Muchachos de vBrownBagLATAM ðŸ˜Š

Alternative method to P2V large volumes/LUNs

When P2V'ing a server that uses large LUNs for one or more of its volumes, there is an alternative method I have found very practical as it takes less time for initial conversion, allowing me to validate that the OS will load and work fine, quicker. 
There have been instances when, after a long P2V process, the VM doesn't work well for whatever reason and the whole conversion time was essentially lost; if it included few terabytes of data, we could be talking of many hours wasted.

Let's say you have a physical Windows system you wish to convert to virtual and it contains multiple volumes/LUNs. If one or more of the volumes are very large, say more than 1TB; I have found that excluding them in the original conversion is better in some specific cases... WHAT? What are you thinking? Why would you do that?   Read on...

The approach is to exclude the large volume(s) during the P2V task and once you have it as a virtual machine and the source system is powered off, map that same LUN or LUNs from your SAN to the ESXi nodes hosting your new Virtual Machine, then present the LUN as a Virtual RDM to your VM. Following this, power on the VM and make sure you can logon to your virtual Windows system, have no issues mounting and accessing the volume normally inside the guest OS. Finally in order to make that last volume also virtual, you perform a Storage vMotion only for the Virtual RDM disk, making sure you select the Advanced section from the wizard and pick either Thin or Thick Provisioning type for the destination.

After the Storage vMotion completes, the original source LUN will still be there in your SAN and you need to unmap it from your hosts and recycle it or do whatever you plan to do with it. 





Schedule tasks right from the menus of the Web Client.

Did you know that a few actions for vCenter objects can be easily scheduled and that the option is readily accessible from Web Client menus?

A handful of tasks can be configured to run at a later time with a simple trick: when you expand the menu for an specific object, either by right-clicking the object or selecting 'Actions' drop-down, press and hold the CTRL key and you'll see a clock for the actions that support setting a schedule.


You must click the action while keeping the CTRL key pressed in order to see the Scheduling options, otherwise it won't appear.
 

The wizard will have the section to set the schedule for the intended task. Click the 'Change' option to configure the scheduler. 

SRM Bubble Test - Automate IP settings different from those in the Recovery Plan

The capabilities of PowerShell/PowerCLI always intrigue me; when I'm tasked with any project or objective where its usage saves time, increases consistency and makes work more efficient, I look for methods to integrate it. Not being exceptionally proficient with it requires me to often research and test, but it's well worth it when the results achieve the target goal consistently and productivity improves.

I was once involved in repetitive, planned Disaster Recovery Tests (Bubble Tests) that had a very specific requirement: The failed over VMs in the isolated network needed to have IP settings that varied from the settings of their SRM Recovery Plans. Changing the actual Recovery Plan settings for each one of the involved VMs and groups was not allowed - If there was ever a need for a true fail over event and the Recovery Plan was modified, that would not have been good, plus that would mean changing the entries back after the tests completed.
Initially the IP, Default Gateway and DNS values for the VMs in the 'Bubble' were manually changed from the console; this method consumed a lot of time as we needed to do it for multiple machines, it was prone to errors and had to be done every time the Bubble Tests were ran.

Invoke-VMScript cmdlet, is an amazing tool! 

The goal was to change IP, Subnet, Default Gateway and DNS values. Since the bubble tests were repeated, it was worth taking the time to build the commands for each VM.

Cleaning up Standard Switches with PowerCLI after migrating to VDS

PowerShell and PowerCLI are such a wonderful tools for so many things. I want to share a very simple 'one-liner' that saved me a good amount of time when removing a bunch of Standard Switches from hosts on various vCenters.

Recently I was tasked with migrating hosts and their VMs on a few vSphere environments from Standard Switches to the Virtual Distributed Switch on their corresponding vCenters; the migration part wasn't hard, hosts were added to VDS, then the VMs were hot migrated using the built-in "Migrate Virtual Machine Networking" option of the VDS. Once all was set and done, the Standard Switches and their port-groups, which there were many, needed to be cleaned up, but manually removing one Switch at the time from several hosts wasn't a smart way of doing it - simple from the GUI yes, but not ideal if you have large amount of hosts with a handful of VSS each. So the one-liner that allowed me to remove all Standard Switches from all nodes at once was: 

Remove-VirtualSwitch -VirtualSwitch vSwitch1, vSwitch2, vSwitch3, vSwitch4 -Server vCenterServerName -Confirm:$false 

The syntax for this command allows to enter multiple VSS names separated by comas which is key for removing all intended switches in one shot. Parameter -Confirm:$false avoided the prompt for every deletion and the -Server vCenterServerName option is only required if you are connected to more than one vCenter Server on the current PowerCLI session. You should obviously use caution and test before running a command like this against your production vCenter Server, the -WhatIf parameter is very helpful to confirm that what you want to accomplish with the command is what the result will be.