PowerCLI Poster Giveaway Contest

For the last few months I have really been interested in improving my PowerShell and PowerCLI skills. I've been watching Pluralsight courses and using every opportunity to perform tasks or obtain reports from the command line instead of using the GUI - when time allows :-) 
After seeing the PowerCLI poster available from VMware, I wanted to get my hands on one but after asking the gurus for a copy and finding out they didn't have additional ones, I resorted to printing my own from the PDF VMware provides here.  I ordered 3 posters and they came out very nice... In full (recommended) size 39x19 inches and laminated for durability; here's the one in my cube..


Having a pair extra I wanted to have a contest to give them away, so I initially thought of offering them to anyone who could teach me the best PowerCLI trick, something advanced and useful, but soon I realized that advanced users may not benefit from having the poster as much as someone starting to learn PowerCLI, so the idea changed quickly and an update was posted. Brian Graf and Kyle Ruddy accepted to be the judges at and select the winners few days later.





Many people did not follow the rules and were simply asking for the poster until Brian Graf tweeted this: 

Reporte de VMs con su promedio de CPU

Cuanto más aprendo PowerCLI, mas quiero aprenderlo y practicarlo. Cada que tengo una oportunidad de usarlo para automatizar o crear reportes en vez de otra herramienta que quizás me pueda brindar lo mismo utilizando el GUI, prefiero forzarme a hacerlo desde la línea de comando – es una buena excusa para practicar y mejorar en este lenguaje.

Recientemente mi jefe me pidió un reporte de las máquinas virtuales que son protegidas con Array Replication; él quería que listara el nombre, CPU, memoria, capacidad de disco asignada y el promedio de uso de CPU de cada VM. Las VMs residen en vCenters independientes pero tienen un común denominador y es que residen and datastores que utilizan un nombre propio, o al menos parte del nombre es igual “RPL”, para fácil distinción obviamente.

Dos de las propiedades que deberían estar en el reporte no me resultaba ponerlas en el reporte de una manera visualmente agradable; agregar ProvisionedSpaceGB resultaba en un numero de muchísimos dígitos y conseguir filtrar el promedio de uso de CPU en la última semana no fue inicialmente fácil.
Gracias a Google y los muchos blogers que sin egoísmo comparten scripts y soluciones, pude encontrar la manera correcta de generar el reporte con un One-liner básicamente.

Quiero dejarlo aquí para mi propia referencia, pero también con la esperanza que alguien más lo encuentre beneficioso.


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




Esta parte nos proveé la abilidad de redondear el total de GB envez de presentar un numero con mas de 10 digitos.
@{n="Provisionedspace(GB)";E={[math]::round($_.ProvisionedSpaceGB)}}


Esta parte agrega el premedio de uso de CPU para cada VM en la ultima semana.
@{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)}}




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.