Technical Guides Featured VMware Horizon

Automating VMware Horizon 7 with VMware PowerCLI

General support for VMware Horizon 7 ends April 30, 2023, impacting all versions up to and including VMware Horizon 7.13. Read this blog to understand why and how to upgrade to Horizon 8 now: “Top 8 Reasons to Upgrade to VMware Horizon 8.”

This blog was originally published in January 2017 and updated in January 2020. If you are running VMware Horizon 8, please read this blog.

VMware PowerCLI has integrated PowerShell support for VMware Horizon 7 to allow for programmatic control and automation through the View API.

With the VMware PowerCLI Horizon 7 functionality, we actually get three things: the Horizon 7 PowerCLI module itself, 100 percent access to the View API with online documentation, and a set of advanced functions released on GitHub.

VMware PowerCLI Horizon

VMware PowerCLI – Horizon 7 Module

Even though the Horizon 7 module contains only two cmdlets, they are extremely useful. These cmdlets allow you to connect and disconnect from the View API service. Importantly, this functionality provides a convenient way to access the full View API and all the capabilities available through the Horizon Console.

This allows you to connect and run VMware PowerCLI scripts for Horizon 7 from remote workstations or servers, such as an administrator’s desktop, using different credentials. You can also easily build federated scripts across VMware assets. For example, you can write a script to get a list of datastores from a vCenter Server inventory and use that information to select the best datastores on which to create a pool.

View API

To accompany the new VMware PowerCLI module, there is also public View API Reference Documentation for Horizon 7 and access to the full public View API. The View API is a web service and is available from any Connection Server within a Horizon Pod. The View API is used by the Horizon Console for configuration, administration, and monitoring, so we are now exposing programmatic access to all the functionality available in the console.

To make exploring the data objects and methods of interacting with them easier, VMware has created a new Developer Center online API Explorer, a unified interface for all API documentation across the VMware stack.

Advanced Functions

To get you started quickly, the Horizon 7 team has put together a set of functions that cover common operations. These functions allow you to easily interact with pools, farms, and desktops without having to write scripts from scratch. Be sure to visit the VMware PowerCLI Community Repository site on GitHub periodically to get new functions and consider contributing your own.

Installation

1. Install VMware PowerCLI

a. Download Open a Windows PowerShell (Admin) console and run the following command.

Install-Module VMware.PowerCLI -Scope CurrentUser

b. Allow Execution of Local Scripts

Set-ExecutionPolicy RemoteSigned

c. See the VMware PowerCLI User’s Guide for more information.

https://code.vmware.com/doc/preview?id=633

2. Install the Horizon advanced functions:

a. Go to the GitHub repository page at  https://github.com/vmware/PowerCLI-Example-Scripts.

b. Click the green Clone or download button and then click Download ZIP.

VMware PowerCLI Horizon


c. Extract the zip file and copy the advanced functions Hv.Helper folder to a modules directory.

d. Check your PowerShell $env:PSModulePath variable to see which directories are in use:

User specific: %UserProfile%\Documents\WindowsPowerShell\Modules

• System wide: C:\Program Files\WindowsPowerShell\Modules

e. Unblock the advanced functions to allow them to be executed. In a PowerShell prompt (as Administrator), run the following command, tailoring the path to where you copied the VMware.Hv.Helper folder:

dir ‘C:\Program

Files\WindowsPowerShell\Modules\VMware.HvHelper\’ |

Unblock-File

3. Locate documentation:

• Bookmark the View API Reference Documentation.

• Bookmark the VMware PowerCLI Cmdlets Reference

 Getting Started

Launch PowerShell and load any of the VMware modules required. You can import all of the VMware modules or just the Horizon 7 module, though you need the Core module too if you plan on interacting with VMware vSphere. To load all the modules, use the following command:

Get-Module -ListAvailable VMware* | Import-Module

You can now connect to the Horizon Connection Server and the View API using your credentials:

Connect-HVServer -server horizon1.mydomain.com

In this example, horizon1.mydomain.com is one of the Horizon Connection Servers. You are prompted for credentials, but you could alternatively include your credentials in the command.

Connect-HVServer -server horizon1.mydomain.com -user demoadmin -password mypassword -domain mydomain

VMware PowerCLI Horizon

A global variable called DefaultHVServers is created, which stores information about connections to the Horizon Connection Servers. You can access this variable with $Global:DefaultHVServers.

VMware PowerCLI Horizon

All the interesting stuff is really under ExtensionData. To make working with this property a bit easier we will assign it to a variable $Services1 and take a look.

$Services1=$Global:DefaultHVServers.ExtensionData

$Services1

VMware PowerCLI Horizon

Looking at the View API reference documentation you will start to recognize some of these entries. The ExtensionData property (and now the $Services1variable) holds access to the entire View API.

Examples

Let’s run a couple of commands and start to explore how we can use the VMware PowerCLI. Remember we have access to 100 percent of the View API!

First, let’s use a simple View API command and get a list of all the Horizon Connection Servers in the pod. The commands in the following example use the View API service ConnectionServer and method ConnectionServer_Listand assign the results to variable $hvServers1. For more information about this service, see the View API reference documentation.

$hvServers1 =

$Services1.ConnectionServer.ConnectionServer_List()

$hvServers1.General

VMware PowerCLI Horizon

Next, let’s use one of the advanced functions to get a list of desktops, depending on the state of the Horizon Agent. This listing is useful for understanding the state of the desktops, including whether they are in use, available for new user connections, or in an error state.

The following command returns a list of the desktops which have users logged in but the user is currently disconnected from the desktop:

$DisconnectedVMs = Get-HVMachineSummary -State DISCONNECTED

$DisconnectedVMs | Out-GridView

VMware PowerCLI Horizon

For a complete list of possible states, check out the View API documentation on baseState.

It would be useful to get a list of problem VMs with agent states that include the following:

PROVISIONING_ERROR, ERROR, AGENT_UNREACHABLE, AGENT_ERR_STARTUP_IN_PROGRESS, AGENT_ERR_DISABLED, AGENT_ERR_INVALID_IP, AGENT_ERR_NEED_REBOOT, AGENT_ERR_PROTOCOL_FAILURE, AGENT_ERR_DOMAIN_FAILURE, AGENT_CONFIG_ERROR, UNKNOWN

You can modify the command used above to return a list of desktops with one of these states by replacing the state to check for. For example:

$ProblemVMs = Get-HVMachineSummary -State AGENT_UNREACHABLE

You can take this further and use a script to list desktops with the Horizon Agent in a number of different problem states. You could then carry out tasks to remediate the problems. The following sample script gets all the problem desktops by querying the View API using this advanced function. The script then uses a vSphere command to reboot the problem VMs.

In the script, replace the values for the variables to indicate your Connection Server, user name, and so on.

Also, consider adding a -WhatIf parameter to the Restart-VMGuest command. A -WhatIf parameter shows you the outcome without actually executing the command.

####################################################################
# Get List of Desktops that have Horizon Agent in problem states.
# Reboot the OS of each these.
####################################################################

#region variables
###################################################################
# Variables #
###################################################################

$cs = 'horizon1.mydomain.com' #Horizon Connection Server
$csUser= 'demoadmin' #User account to connect to Connection Server
$csPassword = 'mypassword' #Password for user to connect to Connection Server
$csDomain = 'mydomain' #Domain for user to connect to Connection Server

$vc = 'vcenter1.mydomain.com' #vCenter Server
$vcUser = '[email protected]' #User account to connect to vCenter Server
$vcPassword = 'mypassword' #Password for user to connect to vCenter Server

baseStates = @('PROVISIONING_ERROR',

'ERROR',
'AGENT_UNREACHABLE',
'AGENT_ERR_STARTUP_IN_PROGRESS',
'AGENT_ERR_DISABLED',
'AGENT_ERR_INVALID_IP',
'AGENT_ERR_NEED_REBOOT',
'AGENT_ERR_PROTOCOL_FAILURE',
'AGENT_ERR_DOMAIN_FAILURE',
'AGENT_CONFIG_ERROR',
'UNKNOWN')

#endregion variables

tyle="padding-left: 30px;">#region initialize
###################################################################
# Initialize #
###################################################################
# --- Import the PowerCLI Modules required ---
Import-Module VMware.VimAutomation.HorizonView
Import-Module VMware.VimAutomation.Core

# --- Connect to Horizon Connection Server API Service ---
$hvServer1 = Connect-HVServer -Server $cs -User $csUser -Password $csPassword -Domain $csDomain

# --- Get Services for interacting with the View API Service ---
$Services1= $hvServer1.ExtensionData

# --- Connect to the vCenter Server ---
Connect-VIServer -Server $vc -User $vcUser -Password $vcPassword
#endregion initialize

#region main
###################################################################
# Main #
###################################################################
Write-Output ""
if ($Services1) {

foreach ($baseState in $baseStates) {
# --- Get a list of VMs in this state ---
$ProblemVMs = Get-HVMachineSummary -State $baseState

foreach ($ProblemVM in $ProblemVMs) {

$VM = Get-VM -Name $ProblemVM.Base.Name
# --- Reboot each of the Problem VMs ---
Restart-VMGuest -VM $VM
# Add -WhatIf to see what would happen without actually carrying out the action.
}
}

Write-Output "", "Disconnect from Connection Server."
Disconnect-HVServer -Server $cs
} else {
Write-Output "", "Failed to login in to Connection Server."
pause
}

# --- Disconnect from the vCenter Server ---
Write-Output "", "Disconnect from vCenter Server."
Disconnect-VIServer -Server $vc
#endregion main

Summary

These have been fairly simple examples, but these and the installation instructions should be enough to get you going. These examples only scratched the surface of what is possible. Now that you are armed with the PowerCLI module for Horizon, access to the View API, the documentation, and the advanced functions, you can start to explore new ways of automating your Horizon 7 environment.

Let us know how you get on, what use cases and problems you solve, and be sure to feed your scripts back into the community for others to benefit from.