Tag Archives: PowerCLI

Monitoring processes inside a vm with PowerCLI

As part of a large scale data analysis project I was working on recently I used Horizon View and Instant clones to allow me to deploy hundreds of VMs based on my original templated VM which had my app I wanted to use to take in the data, transform it and then return a result. Its important to note that this app was never written to work in a batch mode, it literally took one input and gave an output based on a number of factors.

Whilst this post is not about the benefits of Instant Clones, let me tell you, once I had the original template VM working correctly and optimized for performance it worked like a charm, there is something to be said for the simplicity and efficiency of instant clones and the memory sharing techniques it uses to be able to run hundreds of essentially the same VM.

Once I had these VMs deployed via Horizon I could easily send a job to each VM and tell it to run the job, as these jobs however took an indeterminate amount of time to crunch the data, I needed a way to monitor them and let me know when all the jobs had finished on all the VMs so I could pull the data to analyze it.

First I went down the route of using Invoke-VMScript to hook inside the VM’s and see if the process was running, this however took a long time to complete on 100’s of virtual machines and the monitoring job often took over 20 minutes to monitor the VMs and tell me if the job was completed… far too long for what I needed. So after some googling I learned from my good friend William Lam that there was a new API available that through VMtools would update the GuestInfo with the processes running inside the VM on a configurable timely basis (see his post here), this allowed me to essentially push the information externally to the VM Guest Operating system and grab the info when I needed it to see if my process was running.

William had also written a handy function which I adjusted to work with an array of VMs and tell me if the process was running.

Using these new found skills I was easily able to write a function that allowed me to pull the running processes from the VMs and remove them from the list as that process finished inside the VM, for the icing on the cake I even got it to update me in slack on how it was doing 😉

So i thought I would share this script and encourage you to think about using this way which is much easier and a more performant way to pull the results of the running processes..

Monitoring Script

Function Send-SlackMessage ($Channel = "#MyProjectChannel", $Message) {
        
    $payload = @{
        "channel"    = $Channel
        "icon_emoji" = ":datacenter:"
        "text"       = $Message
        "username"   = "DC Script"
    }

    Invoke-WebRequest `
        -UseBasicParsing `
        -Body (ConvertTo-Json -Compress -InputObject $payload) `
        -Method Post `
        -Uri "https://myslackhookurl" | Out-Null
}

Function Get-VMApplicationInfo {
<#
    .DESCRIPTION Retrieves discovered applications running inside of a VM
    .NOTES  Author:  William Lam
    .NOTES  Site:    www.virtuallyghetto.com
    .NOTES  Reference: http://www.virtuallyghetto.com/2019/12/application-discovery-in-vsphere-with-vmware-tools-11.html
    .PARAMETER VM
        VM Object
    .PARAMETER Output
        CSV or JSON output file
    .EXAMPLE
        Get-VMApplicationInfo -VM (Get-VM "DC-01")
    .EXAMPLE
        Get-VMApplicationInfo -VM (Get-VM "DC-01") -UniqueOnly
    .EXAMPLE
        Get-VMApplicationInfo -VM (Get-VM "DC-01") -Output CSV
    .EXAMPLE
        Get-VMApplicationInfo -VM (Get-VM "DC-01") -Output JSON
#>
    param(
        [Parameter(Mandatory=$true)]$VM,
        [Parameter(Mandatory=$false)][ValidateSet("CSV","JSON")][String]$Output,
        [Parameter(Mandatory=$false)][Switch]$UniqueOnly
    )

    $appInfoValue = (Get-AdvancedSetting -Entity $VM -Name "guestinfo.appInfo").Value

    if($appInfoValue -eq $null) {
        Write-Host "Application Discovery has not been enabled for this VM"
    } else {
        $appInfo = $appInfoValue | ConvertFrom-Json
        $appUpdateVersion = $appInfo.updateCounter

        if($UniqueOnly) {
            $results = $appInfo.applications | Sort-Object -Property a -Unique| Select-Object @{Name="Application";e={$_.a}},@{Name="Version";e={$_.v}}
        } else {
            $results = $appInfo.applications | Sort-Object -Property a | Select-Object @{Name="Application";e={$_.a}},@{Name="Version";e={$_.v}}
        }

        Write-verbose "Application Discovery Time: $($appInfo.publishTime)"
        if($Output -eq "CSV") {
            $fileOutputName = "$($VM.name)-version-$($appUpdateVersion)-apps.csv"

            Write-Host "`tSaving output to $fileOutputName"
            ($appInfo.applications) | ConvertTo-Csv | Out-File -FilePath "$fileOutputName"
        } elseif ($Output -eq "JSON") {
            $fileOutputName = "$($VM.name)-version-$($appUpdateVersion)-apps.json"

            Write-Host "`tSaving output to $fileOutputName"
            ($appInfo.applications) | ConvertTo-Json | Out-File -FilePath "$fileOutputName"
        } else {
            $results
        }
    }
}


Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -ErrorAction SilentlyContinue -Confirm:$false -DisplayDeprecationWarnings $false | out-null
$ProgressPreference = 'SilentlyContinue'


Connect-viserver vcsa-01a.myenv.local -username Administrator@vsphere.local -password VMware1! | Out-Null
$vms = get-vm InstantCloneVM* | Where-Object {$_.PowerState -eq "PoweredOn"} | Sort-Object Name
Send-Slackmessage -message "Monitor Job Started" 
do {
    foreach ($vm in $vms) {
        Write-Host "Checking $VM status..."
        $result = Get-VMApplicationInfo -VM $VM| Where { $_.Application -eq "MyAppProcess.exe" }
        if (!$result){
            Write-Host "Removing $vm as it has completed"
            $vms = $vms | where { $_.Name -ne $vm.name}
        } else {
            Write-Host "$vm still running"
        }
        if (($vms.count -lt 10) -and (! $sentmail)){
            Send-Slackmessage -message "Less than 10 Sigma VMs left"
            $sentmail = $true
        }
    }
    if (! ($oldnumvms -eq ($vms.count))){
        Send-Slackmessage -message "$($vms.count) VMs still running"
    }
    start-sleep -s 30
    $oldnumvms = $vms.count
}
while ($vms)
Send-Slackmessage -message  "All Jobs Completed"

New Year, New Look vCheck

Its been a while since I blogged about vCheck but that doesn’t mean there has been lots of work ongoing with the project, in fact there has been multiple releases and hundreds of pull requests with great new plugins checking for even more issues with your vCenter and lots of bug fixes, in fact this project and the community updating and using it is awesome, here are some the current stats:

  • 954 Commits
  • 64 Contributors (Thanks to all here)
  • 66 Open Issues and 269 Closed Issues

Whats more, one of the most recent releases 6.25 here includes a great new look, the new look is based upon VMwares Clarity framework and personally I think it looks fantastic as you can see below:

vCheck Clarity

Also available (currently in the dev branch) is the brand new dark version of the theme as seen below:

vCheck Clarity Dark

Download for free now!

Download the latest version here:  https://github.com/alanrenouf/vCheck-vSphere/archive/master.zip

And the dev branch version here: https://github.com/alanrenouf/vCheck-vSphere/archive/dev.zip

 

Checking you are up to date with PowerCLI

Now that PowerCLI is a module and in the PowerShell Gallery there have been a lot of releases and bug fixes, you would be forgiven for not having the latest version installed or even knowing what the latest version is.

With this in mind and with the latest 6.5.3 version triggering this in my mind, I created a function that checks your installed PowerCLI version against the one thats in the PowerShell Gallery online and lets you know if there is a new version.

Now of course this can be run manually and it will return the results letting you know which modules are out of date:

And once completed of course its easy to update PowerCLI to the latest version:

Even better why not add it to your profile. It does take a couple of seconds to run so maybe you will want to run it on a certain day past a certain time in your profile so it doesn’t slow down every launch of PowerShell you have, here is an example of what I have in my profile where I check every Wednesday after 2PM.

if ( ((Get-Date).tostring('%H') -ge "14" ) -and ( (Get-Date).DayofWeek -eq "Wednesday" ) ) {
        Check-PowerCLIUpdate
}

Check-PowerCLIUpdate Script

Here is the function that allows you to check for updates:

Function Check-PowerCLIUpdate {
    #Based on great module by Jeff Hicks here: http://jdhitsolutions.com/blog/powershell/5441/check-for-module-updates/
    [cmdletbinding()]
    Param()

    # Getting installed modules
    $modules = Get-Module -ListAvailable VMware* | Sort Version -Descending | Select-object -Unique

    #Filter to modules from the PSGallery
    $gallery = $modules.where({$_.repositorysourcelocation})

    # Comparing to online versions
    $AllUpdatedModules = @()
    foreach ($module in $gallery) {

         #find the current version in the gallery
         Try {
            $online = Find-Module -Name $module.name -Repository PSGallery -ErrorAction Stop
         }
         Catch {
            Write-Warning "Module $($module.name) was not found in the PSGallery and therefore not checked for an update"
         }

         #compare versions
         if ($online.version -gt $module.version) {
            $AllUpdatedModules += new-object PSObject -Property @{
                Name = $module.name
                InstalledVersion = $module.version
                OnlineVersion = $online.version
                Update = $True
                Path = $module.modulebase
             } 
         }
    }
    $AllUpdatedModules | Format-Table
    #Check completed

}

Retrieving NVMe details through PowerCLI

Recently I was contacted and asked if there was a way to retrieve information about the NVMe Drives in an ESXi host, this information is easily accessible via ESXCLI using the “nvme” namespaces.

Through PowerCLI this can be easily called and then each feature can be called under this namespace to give you detailed information on the NVMe devices in your ESXi host.  The reason they wanted to do this was to first check the firmware on all the NVMe devices in a cluster to see if they are at the latest revision.  Another reason they wanted this script was in case one of the NVMe devices was behaving differently than the others it would be an easy way to compare the devices.

You can see an example of the script running below:

Continue reading

Automating the VSAN HCL with PowerCLI

Recently I was contacted by a customer who needed to be able to update their VSAN Hardware Compatibility List in the VSAN Health Check but was unable to do so via the GUI as their vCenter servers did not have internet access.

This is a common setup as a lot of customers clearly do not want their Server infrastructure having a direct connection to the internet due to strict security requirements. The problem is when the vCenter server needs to update the VSAN HCL database file it requires a connection to the internet to do this. Whats more, this specific customer had several VCs and was getting quite frustrated with the warning that the HCL database had not been updated. Rather than turning this feature off the customer was looking for a way to update the HCL from a computer that had internet access – his desktop.

New in PowerCLI 6.5 (backwards compatible to previous versions) is a cmdlet that will help us achieve this… Update-VSANHCLDatabase, as you can see from the below image this can be run either grabbing the database information directly from the internet or if you add the “FilePath” parameter you can load the database locally.

Continue reading

Automating the build of your vSphere 6.5 home lab

This year at VMworld SFO and BCN I was involved in organizing a couple of great hackathons with the @VMwareCode guys and William Lam, these were highly successful and I have to say the highlight of both my VMworlds.  The teams were great, the end projects were fantastic and most of all, everyone that attended told me they learned something, this if you ask me was the main objective for the hackathon.

If you attended I do want to extend a huge thanks for joining in, having fun and learning with us.

credc8rusaa8un0

To put the hacakthon together we needed to build up some environments for people to use, William came up with the idea of using Intel NUCs as these were easily transportable and packed a punch for their size, the equipment we purchased is listed below:

Quantity: 2 Crucial 16GB Single DDR4 2133 MT/s (PC4-17000) SODIMM 260-Pin Memory – CT16G4SFD8213
Quantity: 1 Intel NUC Kit NUC6i3SYH BOXNUC6I3SYH Silver/Black
Quantity: 1 Samsung 850 EVO 500GB 2.5-Inch SATA III Internal SSD (MZ-75E500B/AM) (For Capacity)
Quantity: 1 Samsung SM951 128 GB Internal Solid State Drive MZHPV128HDGM-00000 (For Performance)

For the hackathon we needed to build a lot of these units, whilst we did some parts of it manually William and I recently took the time to complete the automated deployment of these units, in fact the script is not specific to these units, it will work on any ESXi host with 2 disks, one for performance and 1 for capacity.  Of course you can also adjust the script to use more disks if you have them!

Once you have ESXi on a USB insert it into the machine and configure it to boot from the USB, after the ESXi machine is on the network you can alter the configuration settings in the start of the script and run the script in the Deployment Script section of this blog to automate the following:

  • Configure VSAN in a single node configuration (Unsupported)
    • Use the smaller SSD for performance
    • Use the larger SSD for Capacity
  • Configure NTP on the ESXi Host
  • Enable SSH on the ESXi Host for debugging
  • Configure the Syslog settings on the ESXi Host
  • Deploy the VCSA on the ESXi Host
  • Enable VSAN Traffic on the Management Network
  • Create a Datacenter
  • Create a Cluster
  • Create a subscribed content library for William Lams Nested ESXi Library
  • Enable Autostart so the VCSA VM starts when the ESXi machine powers on
  • Enable SSH on the VCSA Server

Continue reading

Working with maintenance mode in vROPs via PowerCLI

A while back I was contacted by someone who knew that PowerCLI now worked with vRealize Operations (vROPS) and knew it covered the entire API but was unsure how to get to the point where they could achieve what they wanted.

Before I go into what they were doing I highly recommend that if you are interested in learning what is available via VROPs and PowerCLI you check out the following awesome posts by John Dias

And specifically check out this post which tells you the more advanced feature of being able to access the entire API and create your own functions.

So, the story around this script was that this person was heavily using vROPs in their environment to monitor and troubleshoot their VMware infrastructure, they had it highly tuned but also used PowerCLI to automate some maintenance and updates of the infrastructure, the problem was that every time they performed these tasks they would get automated alerts from vROPs to tell them that things were down or not behaving correctly.

This while expected was clearly a pain as we all know that unwanted email from a monitoring system can get tedious and eventually ignored to the detriment of something important being missed.

Continue reading

Adding a vGPU For a vSphere 6.0 VM via PowerCLI

I had a conversation with a VMware customer the other day and they were asking if there was a way to automate the addition and removal of a vGPU to a VM dynamically on a requested or scheduled basis, VMGuru has a great post here on what exactly a vGPU is, I highly recommend reading it.

They asked for a PowerCLI command or function to configure the VM graphics card, specifically to assign a vGPU resources to the VM, a desktop user’s VM is configured by default with vSGA (to not tie up  vGPU resources) then the user schedules the vGPU resource for a specific time frame using their end user portal, before the scheduled vGPU reservation time frame the user is logged out and the script would kick in. The script would reconfigure the VM settings and assigns a vGPU profile to it, the equivalent of what is being done in the UI as follows:

image

Continue reading

PowerCLI 6.0 R2 – The most advanced version VMware has ever made

imageThis week VMware released a new version of PowerCLI and this release is the most advanced version ever made.  As the Product Manager for PowerCLI I am particularly proud of this release as we not only add core functionality to the vSphere cmdlets allowing access to report, manage and automate even more of the core infrastructure but yet again we introduce a number of new features allowing PowerCLI to reach even further into the SDDC and automate and integrate more products.

I always like to ask people what they want to see from PowerCLI next and for a long time now people have been talking to me about vROPs and telling me their use cases of being able to use the rich dataset and analytics provided by vROPs to make decisions and take further action with PowerCLI, something as simple as monitoring a web server to know when it is under duress and provision many more based on these statics all the way to being able to take action on storage systems by monitoring the workload over time.  The use cases are endless and now achievable by the latest version of PowerCLI.  More on this to come in a future post but lets just say I am excited to see what the awesome PowerCLI community does here.

There is so much to talk about in this release, I wanted to give you an overview in this post and then dive deeper into some of the key features in the future.

What’s New?

More Module Enhancements

The community made it clear that we had to move to modules, and whilst we are still getting there, in this release we made even more module enhancements, both to the core distribution model of PowerCLI cmdlets and also converting more of our code base from snapins to modules. In this version the License snap-in has been converted to a PowerShell module. In the new release the PowerCLI Modules have also been moved to the System PSModulePath allowing all users of a machine to access them once installed.

vROPS Support

As briefly mentioned above, a new module and cmdlets have been added to this release to allow access to vRealize Operations, access to the entire public API is available from the $global:DefaultOMServers variable using the ExtensionData property and full cmdlets have been included for the most used features, this gives us a good mix of fully functional easy to use cmdlets and yet the access for advanced users to be able to access the entire API through the ExtensionData property to create their own functions to expose anything to automate vROPs.  The following cmdlets were added for using with vROPs:

  • Connection: Connect-OMServer , Disconnect-OMServer
  • Alerts: Get-OMAlert, Get-OMAlertDefinition, Get-OMAlertSubType, Get-OMAlertType, Set-OMAlert
  • Recommendations: Get-OMRecommendation
  • Resources: Get-OMResource
  • Statistics: Get-OMStat, Get-OMStatKey
  • User Management: Get-OMUser

Update Manager

PowerCLI for Update Manager has always been available as a separate downloadable installer but it was hard to work with, you needed to work out which version of Update Manager you had installed on the server and install the exact version of PowerCLI cmdlets to work with it, this was obviously a pain when using multiple versions of vCenter or when trying to manage them from one machine.  In this version PowerCLI for vSphere Update Manager is no longer a separate downloadable component or installer and is now included in the core PowerCLI installer, it is selected by default during the PowerCLI install wizard which allows for simpler and quicker deployment and management of VMware products through PowerCLI. Enhancements have also been made to ensure a better backwards compatibility experience of this module and now supports versions of vSphere Update Manager all they back to 5.5.

vCloud Air

In the previous release we introduced PowerCLI for vCloud Air, allowing you to connect to your dedicated resources you have purchased and transfer your automation skillset into the cloud.  In this release you can now also connect to and manage vCloud Air On-Demand (vCA) instances with the –VCA parameter added to the Connect-PIServer and the new Get-PIComputeInstance cmdlet to list all available compute instances. Existing cmdlets for managing vCloud Director and vCloud Air can be used to work with vCloud Air On-Demand where applicable. Additional to these enhancements a new cmdlet has been added to make it easier and enhance the ability to work with OrgVDC Networks called Get-OrgVdcNetwork.

ESXi Host Hardware

This feature was asked for in the PowerCLI Communities, this is just one of the places we monitor to work out what our future releases look like.  New cmdlets have been added to work with ESXi host hardware, these cmdlets give the ability to interrogate your ESXi hosts and provide core system and hardware information.

Two new cmdlets have been added to work with this area:

  • Get-VMHostHardware lists host information
  • Get-VMHostPCIDevice lists all PCI Devices

Storage

Over the last number of releases we keep making enhancements to the storage cmdlets, with VSAN, IO Filters and now a number of enhancements have been made to the storage module introducing new cmdlets for working with VMware vSphere® API for Storage Awareness (VASA), NFS 4.1 and updated vSphere API for IO Filtering (VAIO) cmdlets.

The following new additional cmdlets are now available:

  • New VASA Cmdlets : New-VasaProvider, Remove-VasaProvider, Get-VasaProvider and Get-VasaStorageArray
  • New NFS Cmdlets: New-NfsUser, Remove-NfsUser, Get-NfsUser and Set-NfsUser
  • Added VAIO filters Cmdlet: Set-VAIOFilter

A pet peeve of mine and others

In previous versions of PowerCLI when you started the interactive shell it would always start PowerCLI in the directory where we installed the components, as I watched people use PowerCLI I would see them run a CD\ to get back to the root of the C: or they would use it from the install directory and often their commands would line wrap making it slightly harder to read, a small but hugely beneficial change was made in this release, the PowerCLI starting directory has now been changed from the full install path of PowerCLI to the root of the installation drive.

Business as usual

As usual updates have been made for PowerCLI to support the latest versions of the software it works with, in this case Site Recovery Manager (SRM) was updated to 6.1 and additional functionality has been added to discover SRM servers when they are deployed in a “shared recovery model” and support has been added for the vCloud Director 8.0 features which are provided by the backwards compatibility agreement of the VCD API.  All this and many more bug fixes and speed enhancements.

What an awesome release!

VMworld 2015–San Francisco–PowerCLI Session

Firstly, I want to say I had a blast at VMworld SFO this year, it was a fantastic show and it really felt like everyone was buzzing with excitement and interest in VMware, the announcements, the partners and just about everything else that was going on.  I think this may be one of my favorite years to date.

 

On top of the general excitement there was of course the awesome group discussions, meet the experts, sessions and customer meetings which I took part in, I was lucky enough to present on some awesome topics this year, the normal PowerCLI deep dive I give with Luc (see below) and also a fantastic new technology called Instant Clone (AKA VMfork). The instant clone presentation is not yet available but for those who are into PowerCLI I wanted to let you know that Luc and my session was made available for everyone to view via PowerCLI, including the information we gave on best practices and also a technical preview of PowerCLI.

 

If you are going to VMworld Barcelona do not worry, we are already adjusting our session to be even better with more best practices and even more information on the awesomeness of PowerCLI.  Well worth attending and watching this as well.