Question

In: Computer Science

Write powershell scripts to connect to Horizon View server, list all users and last time logged...

Write powershell scripts to connect to Horizon View server, list all users and last time logged in, and list virtual machines powered on and off.

Powershell scripts to connect to Vmware horizon 7 and get list of users and VM's in pod.

Solutions

Expert Solution

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.

Mware 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.

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

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

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.

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

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

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

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


Related Solutions

                      Contact Manager COMMAND MENU ---------------------------------------------------------- list - Display all contacts view - View
                      Contact Manager COMMAND MENU ---------------------------------------------------------- list - Display all contacts view - View a contact add - Add a contact del - Delete a contact exit - Exit program Command: list 1. Tom van Rossum 2. Edward Idle Command: view Number: 2 Name: Edward Idle Email: [email protected] Phone: +44 20 7946 0958 Command: add Name: John Smith Email: [email protected] Phone: 559-123-4567 John Smith was added. Command: list 1. Tom van Rossum 2. Edward Idle 3. John Smith Command: exit...
Use list/link list and write in C++ Food ordering system 1. Place Order 2. View the...
Use list/link list and write in C++ Food ordering system 1. Place Order 2. View the food details 3. Modify food details 4. Delete food details 5. Exit Order should let the customer to enter the food code, flavor, weight(kg), unit price, qty, customer ID, name, address and contact number. It will also have an order id automatically assigned with a unique ID when new order is added. When view the food details, it should also calculate the unit price...
1. Where can you go to view a list of all FactSet hotkeys? A. Excel >...
1. Where can you go to view a list of all FactSet hotkeys? A. Excel > FactSet ribbon > Settings > Spreadsheet Tools B. Excel > FactSet ribbon > Settings > Modeling Tools C. Excel > FactSet ribbon > Settings > Manage Hotkeys D. Excel > FactSet ribbon > Help > FactSet’s Excel Tips and Tricks 2. What hotkey modifies a formula in the Edit tab of Sidebar? A. CTRL+M B. CTRL+J C. ALT+M D. ALT+N
Are all genes turned on all the time in all cells? Why or why not? (write...
Are all genes turned on all the time in all cells? Why or why not? (write down).
Write a function which receives a list and returns a number. In the list, all numbers...
Write a function which receives a list and returns a number. In the list, all numbers have been repeated twice except one number that is repeated once. The function should return the number that is repeated once and return it.write a python program for this question. use main function.
Use linked list and write in C++ Food ordering system 1. Place Order 2. View the...
Use linked list and write in C++ Food ordering system 1. Place Order 2. View the food details 3. Modify food details 4. Delete food details Order should let the customer to enter the food code, flavor, weight(kg), unit price, qty, customerID, name, address and contact number. It will also have an order id automatically assigned with a unique ID when new order is added. When view the food details, it should also calculate the unit price * qty as...
Use linked list and write in C++ Food ordering system 1. Place Order 2. View the...
Use linked list and write in C++ Food ordering system 1. Place Order 2. View the food details 3. Modify food details 4. Delete food details Order should let the customer to enter the food code, flavor, weight(kg), unit price, qty, customerID, name, address and contact number. It will also have an order id automatically assigned with a unique ID when new order is added. When view the food details, it should also calculate the unit price * qty as...
We have a list of runner and their running time, write a program in Java to...
We have a list of runner and their running time, write a program in Java to show the fastest runner and their time.
Lately Jennifer is hungry all the time. She read on a Web site last night that...
Lately Jennifer is hungry all the time. She read on a Web site last night that if she limits her total fat intake to no more than 10% of her total calories, she can eat all the carbohydrates and protein that she wants, and she won’t gain weight. So Jennifer went right out to the yogurt shop down the street and ordered a large sundae with nonfat vanilla yogurt and fat-free chocolate syrup. She had to admit, though, that an...
Provide a list of all structures that glomerular filtrate will pass through from the time it...
Provide a list of all structures that glomerular filtrate will pass through from the time it leaves the bloodstream in the glomerular capsule to the time it leaves the body. Ensure that your structure list is in order.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT