New Horizon Golden Image Deployment Tool released

Today at VMware Explore I have launched a new version of the Horizon Golden Image Deployment Tool aka hgidt. This new version is a complete rewrite of the old one as I moved the code base to Python. As base I used a converted framework of the old tool (using ChatGpt :D) in Tkinter and my existing python module for Horizon.

Why the rewrite?

I decided for a rewrite as I wante dto be able to publish the tool as an app and most anti malware tools will flag an exeutable that turns out to be a powershell script as malicious. Besides that I thought it would be easier to make the tool more flexible and more important faster. I also wanted to be able to use it from a mac. While the tool itself works flawless when started as a script I did run into issues compiling it into a Mac App so for now I don’t have that yet.

Changes

  • Switch from Powershell 7 to Python
  • replaced the selector for machines to deploy a secondary image to to a dropdown and number for amount or percentage of machines
  • published as an executable
  • Credentials storing made optional
  • Moved storing of credentials to the local credentials store
  • Connect button connects and gets info for both VDI & RDS

Where can I get it?

For now a zip file with the executable (and a ton of other files, it was either that or a slower starting app.) can be found on my Github which also has my (messy) source code.

Did anything change in how I use it?

Only some tiny bits like the option that I added to store the password or not and some slight changes on the VDI/RDS but I think these will be self explanatory.

Pics or it didn’t happen

The executable among the 1000’s of other files needed for Python

The configuration page, note the checkbox to store the password.
With the popup to ask for the password
After testing the credentials

The VDI & RDS Tabs after connecting. Take note of the already selected resizing options. These will be read from the current config so you get the same size when redeploying.

After selecting a new snapshot and enabling the secondary image to be pushed to selected machines
Deploy button was hit
And after a refresh

Todo list & bugs

  • FIx the percentage of machines that sometimes fails
  • add more logging
  • find a method to package into an app for macos

Used Python Modules

These are the modules I am using in this application

  • tkinter
  • tkcalendar
  • datetime
  • configparser
  • os
  • horizon_functions (own custom module)
  • keyring
  • requests
  • threading
  • time
  • sys
  • math
  • loguru
  • ttkthemes

Getting Horizon Events using the REST API

In a previous post I described on how to configure the Horizon Event database using the REST API’s. In this post I will describe on how you can retreive those events using a script that I have created. To get the first few events is easy, just use the /external/v1/audit-events api cmdlet and you get the first batch of events in an unsorted fashion. The script that I have created will get the events since a certain date and if you want only gets the types with a certain severity.

The script is created for Powershell 7 and has been tested with 7.3.4

Parameters

I have written 4 parameters into this script, 2 are mandatory and 2 are optional

  • Credential
    • This optional parameter needs to be a credential object from get-credential. If this is not supplied you will be asked to provide credentials in domain\username and password.
  • ConnectionServerFQDN
    • This mandatory parameter needs to be a string object with the fqdn of the connection server to connetc to i.e. server.domain.dom
  • SinceDate
    • This mandatory parameter needs to be a datetime object for the earliest date to get events for. for example use (get-date).adddays(-100) to get events up to 100 days old.
  • AuditSeverityTypes
    • This optional parameter needs to be an array with SeverityTypes to get events for. Allowed types are : INFO,WARNING,ERROR,AUDIT_SUCCESS,AUDIT_FAIL,UNKNOWN.

Usage

First I get my credentials using get-credential, you cna also import them from an xml using import-clixml creds.xml for example

$credentials = get-credential

Next I get all events for the last day using:

.\Horizon_Rest_Get_Events.ps1 -ConnectionServerFQDN pod1cbr1.loft.lab -sincedate (get-date).AddDays(-1) -Credential $credentials

Or just the ERROR and INFO events using:

.\Horizon_Rest_Get_Events.ps1 -ConnectionServerFQDN pod1cbr1.loft.lab -sincedate (get-date).AddDays(-100) -Credential $credentials -auditseveritytypes "ERROR","AUDIT_FAIL"

Yes I had to get back in days some further to get error events.

The Script

The script itself can be found on my github .

Introducing the Horizon Golden Image Deployment Tool

Intro

Some of you might have seen previews on the socials but for the last few months I have been working hard on a GUI based tool to deploy golden images to VMware Horizon Instant Clone Desktop Pools and RDS Farms. This because who isn’t sick and tired of having to go into each and every Pod admin interface to o a million clicks to deploy a few new golden images?

The work started mid December and as usual the first 75% was done pretty quickly so mid January I had a first working version. While I expected a first version that would only support Desktop Pools to be available mid February (Vmug Virtual EUC day someone?) this build actually already had most of the parts in place to support both Desktop Pools and RDS Farms. After this first build my regular work for ControlUp started picking up again so I had less time to fix the numerous bugs that I encountered. Well bugs? Most where logic errors on my part but most of them have been ironed out by now. All in all the version that you can use today has cost me ~80hrs in building & testing and many many more hours thinking about solutions.

Is the tool perfect? Definitely not but it works and it’s more than what we’ve had before and I will be looking into impriving it even more.

The Tool

I guess you got bored with the talking and would like to see the tool now. The content of thos blog post might get it’s own page later for documentation purposes. The tool itself can be downloaded from this GitHub repository. Make sure to grab both the xaml and ps1 files, put them in a single folder and you should be good. The tool entirely runs on Powershell and is using the WPF Framework for the GUI.

Quick jumps:

Requirements

There are only 2 real requirements:

  • Powershell 7.3 or later (for performance reasons I used some PS 7.3 options so the tool WILL break with an older version.)
  • Horizon 8 2206 or later (the reason for this is that otherwise the secondary images wouldn’t be available and that’s a feature I wanted in there for sure.)

Deplying a new golden Image

For normal usage you can just start the ps1 file.

This will bring you to this tab, before the first use though you need to go to the configuration page.

Fill in one of your cconnection servers, credentials and hit the test button. If you have a cloud pod setup the other pods will be automatically detected and make sure to check the Ignore Certificate Errors checkbox in case that’s needed!

If the test was successfull you are good to go to either the Desktop Pools or RDS Farms tabs. Both are almost completely the same so I will only show desktop pools

Hit the connect button and all Instant Clone Pools or Farms from all pods will be auto populated in the first pull down menu.

The second pulldown menu allows you to select a new source VM

And the third pull down the snapshot (I guess you guessed that already, I might need to add labels but they are so ugly in WPF)

To the right you have all kinds of options that you should recognize from the regular gui including add vTPM that was added in Horizon 2206. This checkbox isn’t in the RDS Farms as we currently simply don’t have the option to have Horizon add a vTPM there. If the options are valid ( like more cores that cores/socket and if those numbers will work (can’t do 3 cores and 2 cores per socket!) the Deploy Golden Image becomes available. Hit this to start the deployment, you can check the status by hitting the refresh button. (don’t tell anyone but the functions does exactly the same as a connect)

Handling Secondary Images

By default a secondary image will not be pushed to any machines. Just select the Push As Secondary Image checkbox and hit Deploy Golden Image button.

What you can also do is select one or more of the machines and deploy the Golden Images ot those machines

Once a Secondary Image has been deployed the three other buttons come available.

From top to bottom you can either cancel the secondary image completely, apply the golden image to more desktops (selecting ones that already has it won’t break anything and will just deploy it when possible) and promote the Secondary Image to the Primary golden image for the pool. The latter will cause a rebuild of ALL machines including the ones already running on the image. In the future I will also add a button to configure a machine to run the original image.

Settings and logs location

All settings are stored in an xml file in %appdata%\HGIDTool this includes the password configured in the Settings tab as a regular Encrypted PowerShell Credentials object. If you didn’t hit save on the settings tab this will be automatically done when closing the tool.

In case you want to borrow some of my code the log files contain every API call that I do to get date, push an image or handlke secondary images. This is the same output as you’d get when running in -verbose mode so that’s only needed when you’re troubleshooting the tool.

Horizon 8 (2209) REST API changelog

I have just added a page that lists the Horizon 8 2209 changes in the API’s. If you’re interested in the overall release notes, please see this link.

Some of the changes that stand out are brand new calls related to Radius & SAML settings but also options to bind to a domain, setting up unauthenticated users. licenses and pre-logon settings.

As always, a complete overview of all calls can be found in the API Explorer. But this is a list of the changes.

/config/v1/admin-users-or-groups/permissions get
/config/v1/gssapi-authenticators get
/config/v1/gssapi-authenticators/{id} get
/config/v1/licenses get
/config/v1/pre-logon-settings get
/config/v1/radius-authenticators get
/config/v1/radius-authenticators/{id} get
/config/v1/saml-authenticators get
/config/v1/saml-authenticators/{id} get
/config/v1/true-sso-enrollment-servers get
/config/v1/true-sso-enrollment-servers/{id} get
/config/v1/unauthenticated-access-users get
/config/v1/unauthenticated-access-users post
/config/v1/unauthenticated-access-users/{id} delete
/config/v1/unauthenticated-access-users/{id} get
/config/v2/connection-servers get
/config/v2/connection-servers/{id} get
/config/v2/settings/security get
/config/v3/settings get
/config/v3/settings put
/config/v3/settings/general get
/config/v3/settings/general put
/external/v1/ad-domains/action/bind post
/external/v1/ad-domains/action/update-auxiliary-accounts post
/external/v1/domains get
/external/v2/ad-users-or-groups/action/hold post
/external/v2/ad-users-or-groups/action/release-hold post
/login get
/monitor/v3/gateways get
/monitor/v3/connection-servers get
/monitor/v2/connection-servers/{id} get
/monitor/v2/gateways/{id} get

Horizon 8 API changelog pages now available

Since several version in each VMware Horizon release notes pages there has been this mention:

This links to this page: VMware Horizon REST APIs (84155) for a while this page was updated with the latest additions to the REST api’s but I guess people didn’t want to do that anymore so that page now simply links to the API Explorer:

Since I used this changelog to decide on what I wanted to blog about I thought it was time to create a changelog myself. What I did was download all the swagger specifications and compare them. For reasons I had to do this in excel but at least I now have a nice source for this. (ping me if you would like to have the excel file). This result in a new menu item at the top of my blog with the changelog for every Horizon 8 version. Yes I know the rest api’s have been available since 7.10 but I decided to start with 8.0. Please use the menu on top of the links below to go to the changelog for the version that you would like to see.

Horizon 8.0 (2006)

Horizon 8.1 (2103)

Horizon 8.2 (2106)

Horizon 8.3 (2109)

Horizon 8.4 (2111)

Horizon 8.5 (2203) – no changes

Horizon 8.6 (2206)

 

PowerCLI Script to Horizon Desktop Pool machine counts & provisioning type

A long time ago in a galaxy far way I used to be a freelancer for ControlUp creating Script Actions and that actually helped me in securing a job with this great company. One of the first SBA’s that I made was one to change the amount of machines in a desktop pool. Recently one of our customers asked if it was possible to also control the minimum amount and powered on machines. Today I have updated this sba and it will be published shortly (if it hasn’t been published when you read this hit me up for a preview sba xml file). I took it a step further though and added the option to change the provisioning type. With a small security piece in place to prevent you from accidentally changing the type. Besides this being published as an sba I have also published a script that can be used from any computer using PowerCLI.

To be clear: this script uses PowerCLI with the SOAP api’s so it should work with almost all Horizon Versions since 7.5. If I find the time I will create a REST version but that will only work with Horizon 8 2111 and above.

The parameters:

  • Credentials : This optional parameter needs a credential object from get-credential. If you don’t supply it you will get a popup for credentials
  • HVDesktopPoolname: Required parameter with the name of the Desktop Pool to change
  • HVConnectionServerFQDN: Required parameter with the FQDN for a connection server to connect to
  • Provisioningtype: Optional Parameter if you want to change the provisioning type. Has to be either UP_FRONT or ON_DEMAND
  • ChangeProvisioningtype: optional parameter that needs either $true or $false and defaults to $false if not provided. The script will error if you set this to false while the provisionintype is different from the current one.
  • maxNumberOfMachines: required parameter with the maximum amount of machines
  • minNumberOfMachines: required parameter when using ON_DEMAND as provisioning type for the minimum amount of machines. Validation is done later in the script so it will not ask for an amount if not provided.
  • numberOfSpareMachines: required parameter when using ON_DEMAND as provisioning type for the minimum amount of powered on machines. Validation is done later in the script so it will not ask for an amount if not provided.

Usage:

Set-Desktoppoolmachinecountandtype.ps1 -Credentials $creds  -HVDesktopPoolname Pod01-Pool02 -HVConnectionServerFQDN pod1cbr1.loft.lab -Provisioningtype ON_DEMAND -maxNumberOfMachines 10 -minNumberOfMachines 3 -ChangeProvisioningtype $true -numberOfSpareMachines 4

or

Set-Desktoppoolmachinecountandtype.ps1 -Credentials $creds  -HVDesktopPoolname Pod01-Pool02 -HVConnectionServerFQDN pod1cbr1.loft.lab -Provisioningtype UP_FRONT -maxNumberOfMachines 10 -ChangeProvisioningtype $false

there’s an option to add -verbose for a bit more visibility, I will use this in my screenshots:

Changing the count for an pool that provisions all desktops up front

Changing the count & type but not setting the changeprovisioningtype to $true

Corrected changeprovisioningtype

As usual the script is available on Github or down below

<#
    .SYNOPSIS
    Changes the amount of Desktops in a Horizon Desktop Pool

    .DESCRIPTION
    This script changes the amount of Desktops in a Horizon Desktop Pool.

    .PARAMETER Credential
    Mandatory: No
    Type: PSCredential
    Object with credentials for the connection server with domain\username and password. If not supplied the script will ask for user and password.

    .PARAMETER HVDesktopPoolname
    Name of the Desktop Pool to update

    .PARAMETER Provisioningtype
    Use ON_DEMAND to provision all desktops up front (will ignore minNumberOfMachines and numberOfSpareMachines

    .PARAMETER ChangeProvisioningtype
    User either True or False to enable or disable the changing of the provisioning type

    .PARAMETER maxNumberOfMachines
    Maximum number of desktops in the pool

    .PARAMETER minNumberOfMachines
    Minimum number of desktops in the pool

    .PARAMETER numberOfSpareMachines
    Minimum number of powered on desktops in the pool

    .PARAMETER HVConnectionServerFQDN
    FQDN for a connectionserver in the pod the pool belongs to.

    .EXAMPLE
    Set-Desktoppoolmachinecountandtype.ps1 -Credentials $creds  -HVDesktopPoolname Pod01-Pool02 -HVConnectionServerFQDN pod1cbr1.loft.lab -Provisioningtype ON_DEMAND -maxNumberOfMachines 10 -minNumberOfMachines 3 -ChangeProvisioningtype $true -numberOfSpareMachines 4
    
    .EXAMPLE
    Set-Desktoppoolmachinecountandtype.ps1 -Credentials $creds  -HVDesktopPoolname Pod01-Pool02 -HVConnectionServerFQDN pod1cbr1.loft.lab -Provisioningtype UP_FRONT -maxNumberOfMachines 10 -ChangeProvisioningtype $false

    .EXAMPLE
    Set-Desktoppoolmachinecountandtype.ps1 -Credentials $creds  -HVDesktopPoolname Pod01-Pool02 -HVConnectionServerFQDN pod1cbr1.loft.lab -maxNumberOfMachines 10

    .NOTES
    This script requires VMWare PowerCLI to be installed on the machine running the script.
    PowerCLI can be installed through PowerShell (PowerShell version 5 or higher required) by running the command 'Install-Module VMWare.PowerCLI -Force -AllowCLobber -Scope AllUsers' Or by using the 'Install VMware PowerCLI' script.
    Credentials can be set using the 'Prepare machine for Horizon View scripts' script.

    Modification history:   12/12/2019 - Wouter Kursten - First version
                            26/03/2022 - Wouter Kursten - Added options for on demand provisioning

    .LINK
    https://code.vmware.com/web/tool/11.3.0/vmware-powercli


    .COMPONENT
    VMWare PowerCLI

#>

[CmdletBinding()]
Param
(
    [Parameter(Mandatory=$false,
    HelpMessage='Credential object as domain\username with password' )]
    [PSCredential] $Credentials,

    [Parameter(
        Mandatory=$true,
        HelpMessage='Name of the Desktop Pool'
    )]
    [ValidateNotNullOrEmpty()]
    [string] $HVDesktopPoolname,

    [Parameter(
        Mandatory=$true,
        HelpMessage='FQDN for the connection server'
    )]
    [ValidateNotNullOrEmpty()]
    [string] $HVConnectionServerFQDN,

    [Parameter(
        Mandatory=$false,
        HelpMessage='Provisioning type'
    )]
    [ValidateSet("UP_FRONT","ON_DEMAND")]
    [string] $Provisioningtype,

    [Parameter(
        Mandatory=$false,
        HelpMessage='Change Provisioning type?'
    )]
    [ValidateSet("True","False")]
    [bool] $ChangeProvisioningtype = $false,

    [Parameter(
        Mandatory=$true,
        HelpMessage='Maximum number of machines in the desktop.'
    )]
    [ValidateNotNullOrEmpty()]
    [int] $maxNumberOfMachines,

    [Parameter(
        Mandatory=$false,
        ParameterSetName = 'ondemand',
        HelpMessage='The minimum number of machines to have provisioned if on demand provisioning is selected. Will be ignored if provisioningtype is set to UP_FRONT.'
    )]
    [ValidateNotNullOrEmpty()]
    [int] $minNumberOfMachines,

    [Parameter(
        Mandatory=$false,
        ParameterSetName = 'ondemand',
        HelpMessage='Number of spare powered on machines. Will be ignored if provisioningtype is set to UP_FRONT.'
    )]
    [ValidateNotNullOrEmpty()]
    [int] $numberOfSpareMachines
)

$ErrorActionPreference = 'Stop'

function Load-VMWareModules {
    <# Imports VMware modules
    NOTES:
    - The required modules to be loaded are passed as an array.
    - In versions of PowerCLI below 6.5 some of the modules can't be imported (below version 6 it is Snapins only) using so Add-PSSnapin is used (which automatically loads all VMWare modules)
    #>

    param (
        [parameter(Mandatory = $true,
            HelpMessage = "The VMware module to be loaded. Can be single or multiple values (as array).")]
        [array]$Components
    )

    # Try Import-Module for each passed component, try Add-PSSnapin if this fails (only if -Prefix was not specified)
    # Import each module, if Import-Module fails try Add-PSSnapin
    foreach ($component in $Components) {
        try {
            $null = Import-Module -Name VMware.$component
        }
        catch {
            try {
                $null = Add-PSSnapin -Name VMware
            }
            catch {
                write-error 'The required VMWare modules were not found as modules or snapins. Please check the .NOTES and .COMPONENTS sections in the Comments of this script for details.'
                exit
            }
        }
    }
}

function Connect-HorizonConnectionServer {
    param (
        [parameter(Mandatory = $true,
            HelpMessage = "The FQDN of the Horizon View Connection server. IP address may be used.")]
        [string]$HVConnectionServerFQDN,
        [parameter(Mandatory = $true,
            HelpMessage = "The PSCredential object used for authentication.")]
        [PSCredential]$Credential
    )
    # Try to connect to the Connection server
    try {
        Connect-HVServer -Server $HVConnectionServerFQDN -Credential $Credential
    }
    catch {
        write-error "There was a problem connecting to the Horizon View Connection server: $_."
        exit
    }
}

function Disconnect-HorizonConnectionServer {
    param (
        [parameter(Mandatory = $true,
            HelpMessage = "The Horizon View Connection server object.")]
        [VMware.VimAutomation.HorizonView.Impl.V1.ViewObjectImpl]$HVConnectionServer
    )
    # Try to connect from the connection server
    try {
        Disconnect-HVServer -Server $HVConnectionServer -Confirm:$false
    }
    catch {
        write-error  "There was a problem disconnecting from the Horizon View Connection server: $_"
        exit
    }
}

function Get-HVDesktopPool {
    param (
        [parameter(Mandatory = $true,
        HelpMessage = "Name of the Desktop Pool.")]
        [string]$HVPoolName,
        [parameter(Mandatory = $true,
        HelpMessage = "The Horizon View Connection server object.")]
        [VMware.VimAutomation.HorizonView.Impl.V1.ViewObjectImpl]$HVConnectionServer
    )
    # Try to get the Desktop pools in this pod
    try {
        # create the service object first
        [VMware.Hv.QueryServiceService]$queryService = New-Object VMware.Hv.QueryServiceService
        # Create the object with the definiton of what to query
        [VMware.Hv.QueryDefinition]$defn = New-Object VMware.Hv.QueryDefinition
        # entity type to query
        $defn.queryEntityType = 'DesktopSummaryView'
        # Filter oud rds desktop pools since they don't contain machines
        $defn.Filter = New-Object VMware.Hv.QueryFilterEquals -property @{'memberName'='desktopSummaryData.displayName'; 'value' = "$HVPoolname"}
        # Perform the actual query
        [array]$queryResults= ($queryService.queryService_create($HVConnectionServer.extensionData, $defn)).results
        # Remove the query
        $queryService.QueryService_DeleteAll($HVConnectionServer.extensionData)
        # Return the results
        if (!$queryResults){
            write-error  "Can't find $HVPoolName, exiting"
            exit
        }
        elseif (($queryResults).desktopsummarydata.type -eq "MANUAL"){
            write-output  "This a manual Horizon View Desktop Pool, cannot change the amount of desktops"
            exit
        }
        elseif (($queryResults).desktopsummarydata.source -eq "VIRTUAL_CENTER"){
            write-output  "This a Full Clone Horizon View Desktop Pool, if the amount of desktops has been reduced the extra systems need to be removed manually"
            return $queryResults
        }
        else {
            return $queryResults
        }
    }
    catch {
        write-error  "There was a problem retreiving the Horizon View Desktop Pool: $_"
        exit
    }
}

function get-hvpoolspec{
    param (
        [parameter(Mandatory = $true,
            HelpMessage = "ID of the Desktop Pool.")]
        [VMware.Hv.DesktopId]$HVPoolID,
        [parameter(Mandatory = $true,
            HelpMessage = "The Horizon View Connection server object.")]
        [VMware.VimAutomation.HorizonView.Impl.V1.ViewObjectImpl]$HVConnectionServer
    )
    try {
        $HVConnectionServer.ExtensionData.Desktop.Desktop_Get($HVPoolID)
    }
    catch {
        write-error "There was a problem retreiving the desktop pool details: $_"
        exit
    }
}

function Set-HVPool {
    param (
        [parameter(Mandatory = $true,
            HelpMessage = "ID of the Desktop Pool.")]
        [VMware.Hv.DesktopId]$HVPoolID,
        [parameter(Mandatory = $true,
        HelpMessage = "Provisioning type UP_FRONT or ON_DEMAND")]
        [ValidateSet("UP_FRONT","ON_DEMAND")]
        [string] $Provisioningtype,
        [parameter(Mandatory = $true,
            HelpMessage = "Desired amount of desktops in the pool.")]
        [int]$maxNumberOfMachines,
        [parameter(Mandatory = $false,
        HelpMessage = "Desired amount of spare desktops in the pool.")]
        [int]$numberOfSpareMachines,
        [parameter(Mandatory = $false,
        HelpMessage = "Desired minimum amount of desktops in the pool.")]
        [int]$minNumberOfMachines,
        [parameter(Mandatory = $true,
            HelpMessage = "The Horizon View Connection server object.")]
        [VMware.VimAutomation.HorizonView.Impl.V1.ViewObjectImpl]$HVConnectionServer
    )
    if($Provisioningtype -eq "UP_FRONT"){
        try {
            # First define the Service we need
            [VMware.Hv.DesktopService]$desktopservice=new-object vmware.hv.DesktopService
            # Fill the helper for this service with the application information
            $desktophelper=$desktopservice.read($HVConnectionServer.extensionData, $HVPoolID)
            # Change the state of the application in the helper
            $desktophelper.getAutomatedDesktopDataHelper().getVmNamingSettingsHelper().getPatternNamingSettingsHelper().setMaxNumberOfMachines($maxNumberOfMachines)
            $desktophelper.getAutomatedDesktopDataHelper().getVmNamingSettingsHelper().getPatternNamingSettingsHelper().setProvisioningTime("UP_FRONT")
            # Apply the helper to the actual object
            $desktopservice.update($HVConnectionServer.extensionData, $desktophelper)
        }
        catch {
            write-error "There was a problem changing the desktop count: $_"
            exit
        }
    }
    else{
        try {
            # First define the Service we need
            [VMware.Hv.DesktopService]$desktopservice=new-object vmware.hv.DesktopService
            # Fill the helper for this service with the application information
            $desktophelper=$desktopservice.read($HVConnectionServer.extensionData, $HVPoolID)
            # Change the state of the application in the helper
            $desktophelper.getAutomatedDesktopDataHelper().getVmNamingSettingsHelper().getPatternNamingSettingsHelper().setminNumberOfMachines($minNumberOfMachines)
            $desktophelper.getAutomatedDesktopDataHelper().getVmNamingSettingsHelper().getPatternNamingSettingsHelper().setMaxNumberOfMachines($maxNumberOfMachines)
            $desktophelper.getAutomatedDesktopDataHelper().getVmNamingSettingsHelper().getPatternNamingSettingsHelper().setnumberOfSpareMachines($numberOfSpareMachines)
            $desktophelper.getAutomatedDesktopDataHelper().getVmNamingSettingsHelper().getPatternNamingSettingsHelper().setProvisioningTime("ON_DEMAND")
            # Apply the helper to the actual object
            $desktopservice.update($HVConnectionServer.extensionData, $desktophelper)
        }
        catch {
            write-error "There was a problem changing the desktop count: $_"
            exit
        }
    }
}

write-verbose "Script will change this Desktop Pool: $HVDesktopPoolName"
write-verbose "Script will connect to this Connection Server: $HVConnectionServerFQDN "
if($Provisioningtype){
    write-verbose "Provisioningtype was set to $Provisioningtype"
}
else{
    write-verbose "No ProvisioningType was provided"
}

write-verbose "ChangeProvisioningtype was set to $ChangeProvisioningtype"
write-verbose "New Maximum Desktop Count is $maxNumberOfMachines "
if($minNumberOfMachines){
    write-verbose "minNumberOfMachines was set to $minNumberOfMachines"
}
else{
    write-verbose "No minNumberOfMachines was provided"
}

if($numberOfSpareMachines){
    write-verbose "numberOfSpareMachines was set to $numberOfSpareMachines"
}
else{
    write-verbose "No numberOfSpareMachines was provided"
}

if($Credentials){
    $creds = $credentials
}
else{
    $creds = get-credential
}



# Connect to the Horizon View Connection Server

[VMware.VimAutomation.HorizonView.Impl.V1.ViewObjectImpl]$objHVConnectionServer = Connect-HorizonConnectionServer -HVConnectionServerFQDN $HVConnectionServerFQDN -Credential $creds

# Retreive the desktop pool
$HVPool=Get-HVDesktopPool -HVPoolName $HVDesktopPoolname -HVConnectionServer $objHVConnectionServer
write-verbose  "Retreived information about $HVDesktopPoolname"

# But we only need the ID
$HVPoolID=($HVPool).id

# Retreive the pool spec
$hvpoolspec=Get-HVPoolSpec -HVConnectionServer $objHVConnectionServer -HVPoolID $HVPoolID
$ProvisioningTime=($hvpoolspec).AutomatedDesktopData.VmNamingSettings.PatternNamingSettings.ProvisioningTime
write-verbose "Current provisioningtype = $ProvisioningTime"
write-verbose "Checking if provisioningtype matches the current setting and if I am allowed to change it."
if($Provisioningtype){
    if($ProvisioningTime -ne $provisioningtype -and $changeprovisioningtype -eq $False){
        write-error "Provisioningtype of $provisioningtype does not match the current provisioningtype. Set changeprovisioningtype to True to change the provisioningtype"
        exit
    }
    elseif($ProvisioningTime -ne $provisioningtype -and $changeprovisioningtype -eq $true){
        $Provisioningtype=$Provisioningtype.toupper()
        write-verbose "Changing Provisioningtype to $Provisioningtype"
    }
}
else{
    $Provisioningtype = $ProvisioningTime
}

if($Provisioningtype -eq "ON_DEMAND"){
    write-verbose "Checking if numberOfSpareMachines or minNumberOfMachines is missing"
    if(!$minNumberOfMachines -or !$numberOfSpareMachines){
        write-error "numberOfSpareMachines and minNumberOfMachines are required when using provisioningtype: $provisioningtype"
        exit
    }
}

# We cannot change manual pools so we give a warning about this and exit the script.
if ($hvpoolspec.Type -eq "MANUAL"){
    write-error "Could not execute, this a manual Horizon View Desktop Pool, cannot change the amount of desktops."
    exit
}

# When not all vm's are provisioned up front the max amount of machines can't be lower that the minimum amount or the number of spare machines.
if ($Provisioningtype -eq "ON_DEMAND"){
    if ($numberOfSpareMachines -ge $maxNumberOfMachines -or $minNumberOfMachines -ge $maxNumberOfMachines){
        write-error "Could not execute, the number of desktops cannot be smaller than the minimum amount of desktops or the number of spare desktops"
        exit
    }
}

# Change the desktop count in the pool

if($Provisioningtype -eq "UP_FRONT"){
    write-verbose "Provisioningtype is $Provisioningtype so ignoring minNumberOfMachines and numberOfSpareMachines if they have been added."
    write-verbose  "Trying to change $HVDesktopPoolname to $maxNumberOfMachines desktops."
    Set-HVPool -HVConnectionServer $objHVConnectionServer -HVPoolID $HVPoolID -maxNumberOfMachines $maxNumberOfMachines -Provisioningtype $Provisioningtype
    write-output  "Changed $HVDesktopPoolname to $maxNumberOfMachines desktops all provisioned up front."
}
else{
    write-verbose "Provisioningtype is $Provisioningtype so using minNumberOfMachines and numberOfSpareMachines."
    write-verbose  "Trying to change $HVDesktopPoolname to $maxNumberOfMachines desktops with a minimum of $minNumberOfMachines machines and $numberOfSpareMachines spares."
    Set-HVPool -HVConnectionServer $objHVConnectionServer -HVPoolID $HVPoolID -maxNumberOfMachines $maxNumberOfMachines -Provisioningtype $Provisioningtype -minNumberOfMachines $minNumberOfMachines -numberOfSpareMachines $numberOfSpareMachines
    write-output  "Changed $HVDesktopPoolname to $maxNumberOfMachines desktops with a minimum of $minNumberOfMachines machines and $numberOfSpareMachines spares."
}

# Disconnect from the connection server
Disconnect-HorizonConnectionServer -HVConnectionServer $objHVConnectionServer

 

Sending messages to Horizon Sessions using Powershell & REST api’s

Today I got the question from someone that they where trying to send messages to users but had issues with adding the session id’s to the json. I decided to make a quick and nice script that’s able to send a message to all sessions. This uses the standard functions that I always use, the standard Get-HorizonRestData function that I created in this blog post and two custom functions that I created for this script.

The first new function is get-horizonsessions this function gets all local sessions utilizing the get-horizonrestdata function. As you can see pretty basic nothing fancy about it.

function get-horizonsessions(){
    [CmdletBinding(DefaultParametersetName='None')] 
    param(
        [Parameter(Mandatory=$true,
        HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
        [string] $ServerURL,

        [Parameter(Mandatory=$true,
        HelpMessage='Part after the url in the swagger UI i.e. /external/v1/ad-users-or-groups' )]
        [PSCustomObject] $accessToken
    )

    try{
        Get-HorizonRestData -ServerURL $url -RestMethod "/inventory/v1/sessions/" -accessToken $accessToken
    }
    catch{
        throw $_
    }
    return $results
}

The second one isn’t that more advanced besides that it has a few more parameters including one called $session_ids that requires an array of the session id’s to where you want to send a message. It creates an ordered hashtable that stores the message, message_type and the array of id’s. This hashtable is than converted to a json file and used as the body for the rest call.

function send-horizonmessage(){
    [CmdletBinding(DefaultParametersetName='None')] 
    param(
        [Parameter(Mandatory=$true,
        HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
        [string] $ServerURL,

        [Parameter(Mandatory=$true,
        HelpMessage='Part after the url in the swagger UI i.e. /external/v1/ad-users-or-groups' )]
        [PSCustomObject] $accessToken,

        [Parameter(Mandatory=$true,
        HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
        [array] $Session_Ids,

        [Parameter(Mandatory=$true,
        HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
        [string] $Message,

        [Parameter(Mandatory=$true,
        HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
        [validateset("ERROR","WARNING","INFO", IgnoreCase = $false)]
        [string] $Message_Type
    )
    $jsonhashtable = [ordered]@{}
    $jsonhashtable.add('message',$message)
    $jsonhashtable.add('message_type',$Message_Type)
    $jsonhashtable.add('session_ids',$Session_Ids)

    $json = $jsonhashtable | convertto-json
    try{
        $results = Invoke-RestMethod -Method Post -uri "$ServerURL/rest/inventory/v1/sessions/action/send-message" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) -body $json
    }
    catch{
        throw $_
    }
    return $results
}

Than I use these 2 lines to actually send the message (after authenticating first, duh). If you want to filter the sessions that can be added to the get-horizonsessions or manually do it on the $sessions array. Be aware that there are no names in this array so you need to gather any of the optional id’s first.

$sessions = get-horizonsessions -accessToken $accessToken -ServerURL $url

send-horizonmessage -accessToken $accessToken -ServerURL $url -Message_Type $Message_Type -message $message -Session_Ids ($sessions).id

And this is how you run the entire script.

.\Horizon_send_messages.ps1 -Credential $credential -ConnectionServerFQDN pod1cbr1.loft.lab -Message "retouw.nl test message" -Message_Type ERROR

And the entire script that’s also available at my Various_Scripts/Horizon_send_messages.ps1 at master · Magneet/Various_Scripts (github.com).

<#
    .SYNOPSIS
    Send a message to all user sessions

    .DESCRIPTION
    This script uses the Horizon rest api's to all sessions in a horizon pod

    .EXAMPLE
    .\find_user_assigned_desktops.ps1 -Credential $creds -ConnectionServerFQDN pod2cbr1.loft.lab -message "test message" -message_type "ERROR"

    .PARAMETER Credential
    Mandatory: No
    Type: PSCredential
    Object with credentials for the connection server with domain\username and password

    .PARAMETER ConnectionServerFQDN
    Mandatory: Yes
    Default: String
    FQDN of the connection server to connect to

    .PARAMETER message
    Mandatory: Yes
    Message to send to the users

    .PARAMETER message_type
    Mandatory: Yes
    Message type: INFO, ERROR or WARNING

    .NOTES
    Created by: Wouter Kursten
    First version: 23-12-2021

    .COMPONENT
    Powershell Core

#>

[CmdletBinding()]
param (
    [Parameter(Mandatory=$false,
    HelpMessage='Credential object as domain\username with password' )]
    [PSCredential] $Credential,

    [Parameter(Mandatory=$true,  HelpMessage='FQDN of the connectionserver' )]
    [ValidateNotNullOrEmpty()]
    [string] $ConnectionServerFQDN,

    [Parameter(Mandatory=$true,
    HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
    [string] $Message,

    [Parameter(Mandatory=$true,
    HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
    [validateset("ERROR","WARNING","INFO", IgnoreCase = $false)]
    [string] $Message_Type
)

function Get-HRHeader(){
    param($accessToken)
    return @{
        'Authorization' = 'Bearer ' + $($accessToken.access_token)
        'Content-Type' = "application/json"
    }
}
function Open-HRConnection(){
    param(
        [string] $username,
        [string] $password,
        [string] $domain,
        [string] $url
    )

    $Credentials = New-Object psobject -Property @{
        username = $username
        password = $password
        domain = $domain
    }

    return invoke-restmethod -Method Post -uri "$url/rest/login" -ContentType "application/json" -Body ($Credentials | ConvertTo-Json)
}

function Close-HRConnection(){
    param(
        $accessToken,
        $url
    )
    return Invoke-RestMethod -Method post -uri "$url/rest/logout" -ContentType "application/json" -Body ($accessToken | ConvertTo-Json)
}

function Get-HorizonRestData(){
    [CmdletBinding(DefaultParametersetName='None')] 
    param(
        [Parameter(Mandatory=$true,
        HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
        [string] $ServerURL,

        [Parameter(Mandatory=$true,
        ParameterSetName="filteringandpagination",
        HelpMessage='Array of ordered hashtables' )]
        [array] $filters,

        [Parameter(Mandatory=$true,
        ParameterSetName="filteringandpagination",
        HelpMessage='Type of filter Options: And, Or' )]
        [ValidateSet('And','Or')]
        [string] $Filtertype,

        [Parameter(Mandatory=$false,
        ParameterSetName="filteringandpagination",
        HelpMessage='Page size, default = 500' )]
        [int] $pagesize = 500,

        [Parameter(Mandatory=$true,
        HelpMessage='Part after the url in the swagger UI i.e. /external/v1/ad-users-or-groups' )]
        [string] $RestMethod,

        [Parameter(Mandatory=$true,
        HelpMessage='Part after the url in the swagger UI i.e. /external/v1/ad-users-or-groups' )]
        [PSCustomObject] $accessToken,

        [Parameter(Mandatory=$false,
        ParameterSetName="filteringandpagination",
        HelpMessage='$True for rest methods that contain pagination and filtering, default = False' )]
        [switch] $filteringandpagination,

        [Parameter(Mandatory=$false,
        ParameterSetName="id",
        HelpMessage='To be used with single id based queries like /monitor/v1/connection-servers/{id}' )]
        [string] $id
    )
    if($filteringandpagination){
        if ($filters){
            $filterhashtable = [ordered]@{}
            $filterhashtable.add('type',$filtertype)
            $filterhashtable.filters = @()
            foreach($filter in $filters){
                $filterhashtable.filters+=$filter
            }
            $filterflat=$filterhashtable | convertto-json -Compress
            $urlstart= $ServerURL+"/rest/"+$RestMethod+"?filter="+$filterflat+"&page="
        }
        else{
            $urlstart= $ServerURL+"/rest/"+$RestMethod+"?page="
        }
        $results = [System.Collections.ArrayList]@()
        $page = 1
        $uri = $urlstart+$page+"&size=$pagesize"
        $response = Invoke-RestMethod $uri -Method 'GET' -Headers (Get-HRHeader -accessToken $accessToken) -ResponseHeadersVariable responseheader
        $response.foreach({$results.add($_)}) | out-null
        if ($responseheader.HAS_MORE_RECORDS -contains "TRUE") {
            do {
                $page++
                $uri = $urlstart+$page+"&size=$pagesize"
                $response = Invoke-RestMethod $uri -Method 'GET' -Headers (Get-HRHeader -accessToken $accessToken) -ResponseHeadersVariable responseheader
                $response.foreach({$results.add($_)}) | out-null
            } until ($responseheader.HAS_MORE_RECORDS -notcontains "TRUE")
        }
    }
    elseif($id){
        $uri= $ServerURL+"/rest/"+$RestMethod+"/"+$id
        $results = Invoke-RestMethod $uri -Method 'GET' -Headers (Get-HRHeader -accessToken $accessToken) -ResponseHeadersVariable responseheader
    }
    else{
        $uri= $ServerURL+"/rest/"+$RestMethod
        $results = Invoke-RestMethod $uri -Method 'GET' -Headers (Get-HRHeader -accessToken $accessToken) -ResponseHeadersVariable responseheader
    }

    return $results
}

function get-horizonsessions(){
    [CmdletBinding(DefaultParametersetName='None')] 
    param(
        [Parameter(Mandatory=$true,
        HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
        [string] $ServerURL,

        [Parameter(Mandatory=$true,
        HelpMessage='Part after the url in the swagger UI i.e. /external/v1/ad-users-or-groups' )]
        [PSCustomObject] $accessToken
    )

    try{
        Get-HorizonRestData -ServerURL $url -RestMethod "/inventory/v1/sessions/" -accessToken $accessToken
    }
    catch{
        throw $_
    }
    return $results
}

function send-horizonmessage(){
    [CmdletBinding(DefaultParametersetName='None')] 
    param(
        [Parameter(Mandatory=$true,
        HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
        [string] $ServerURL,

        [Parameter(Mandatory=$true,
        HelpMessage='Part after the url in the swagger UI i.e. /external/v1/ad-users-or-groups' )]
        [PSCustomObject] $accessToken,

        [Parameter(Mandatory=$true,
        HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
        [array] $Session_Ids,

        [Parameter(Mandatory=$true,
        HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
        [string] $Message,

        [Parameter(Mandatory=$true,
        HelpMessage='url to the server i.e. https://pod1cbr1.loft.lab' )]
        [validateset("ERROR","WARNING","INFO", IgnoreCase = $false)]
        [string] $Message_Type
    )
    $jsonhashtable = [ordered]@{}
    $jsonhashtable.add('message',$message)
    $jsonhashtable.add('message_type',$Message_Type)
    $jsonhashtable.add('session_ids',$Session_Ids)

    $json = $jsonhashtable | convertto-json
    try{
        $results = Invoke-RestMethod -Method Post -uri "$ServerURL/rest/inventory/v1/sessions/action/send-message" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) -body $json
    }
    catch{
        throw $_
    }
    return $results
}

if($Credential){
    $creds = $credential
}
else{
    $creds = get-credential
}

$ErrorActionPreference = 'Stop'

$username=($creds.username).split("\")[1]
$domain=($creds.username).split("\")[0]
$password=$creds.password

$url = "https://$ConnectionServerFQDN"

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) 
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

$accessToken = Open-HRConnection -username $username -password $UnsecurePassword -domain $Domain -url $url

$sessions = get-horizonsessions -accessToken $accessToken -ServerURL $url

send-horizonmessage -accessToken $accessToken -ServerURL $url -Message_Type $Message_Type -message $message -Session_Ids ($sessions).id

 

 

 

Creating desktop pools using the Horizon REST Api with Powershell

For years people have been asking, when can we start creating Horizon Desktop Pools using REST? The first years the answers was that there was no REST Api at all but since they added REST in 7.10 Horizon the answer was whenever VMware feels like adding this option. With the recent release of Horizon 8 2111 they have finally added the option to do this. I have created a script that uses a json file as base I grabbed this from the api explorer. But the sample below is already edited down so I can create a simple desktop pool. You can grab my version below or here on Github.

{
  "access_group_id": "daef8c91-fa65-4a39-93aa-24d87d5aca94",
  "allow_multiple_user_assignments": false,
  "customization_settings": {
    "ad_container_rdn": "OU=Pool01,OU=VDI,OU=Pod1,OU=VMware,OU=EUC",
    "customization_type": "CLONE_PREP",
    "do_not_power_on_vms_after_creation": false,
    "instant_clone_domain_account_id": "9f83ed94-4d44-4c9a-abd3-ffc23e7389de",
    "reuse_pre_existing_accounts": true
  },
  "description": "Desktop pool description",
  "display_assigned_machine_name": false,
  "display_machine_alias": false,
  "display_name": "instantclonepool",
  "display_protocol_settings": {
    "allow_users_to_choose_protocol": true,
    "default_display_protocol": "BLAST",
    "grid_vgpus_enabled": false,
    "renderer3d": "MANAGE_BY_VSPHERE_CLIENT",
    "session_collaboration_enabled": true
  },
  "enable_client_restrictions": false,
  "enable_provisioning": false,
  "enabled": false,
  "name": "demo_pool",
  "naming_method": "PATTERN",
  "pattern_naming_settings": {
    "max_number_of_machines": 5,
    "naming_pattern": "Pool-{n:fixed=2}",
    "number_of_spare_machines": 1,
    "provisioning_time": "UP_FRONT"
  },
  "provisioning_settings": {
    "add_virtual_tpm": false,
    "base_snapshot_id": "snapshot-1",
    "datacenter_id": "datacenter-1",
    "host_or_cluster_id": "domain-s425",
    "parent_vm_id": "vm-2",
    "resource_pool_id": "resgroup-1",
    "vm_folder_id": "group-v1"
  },
  "session_settings": {
    "allow_multiple_sessions_per_user": false,
    "allow_users_to_reset_machines": true,
    "delete_or_refresh_machine_after_logoff": "DELETE",
    "disconnected_session_timeout_minutes": 5,
    "disconnected_session_timeout_policy": "AFTER",
    "logoff_after_timeout": false,
    "power_policy": "ALWAYS_POWERED_ON",
  },
  "session_type": "DESKTOP",
  "source": "INSTANT_CLONE",
  "stop_provisioning_on_error": false,
  "storage_settings": {
    "datastores": [
      {
        "datastore_id": "datastore-1",
        "sdrs_cluster": false
      },
      {
        "datastore_id": "datastore-1",
        "sdrs_cluster": false
      }
    ],
    "reclaim_vm_disk_space": false,
    "use_separate_datastores_replica_and_os_disks": false,
    "use_vsan": false
  },
  "transparent_page_sharing_scope": "VM",
  "type": "AUTOMATED",
  "user_assignment": "FLOATING",
  "vcenter_id": "f148f3e8-db0e-4abb-9c33-7e5205ccd360"
}

Essentially using only the json file could be enough to create a pool but I decided to create a powershell script that uses the json as a base and where I add functionality to make it more flexible. You cna supply names for things like datacenter, desktop pool name, display name and description & many others. If you want you can hardcode these names or even the id’s if you like but I have only done that in the json for the, access_group_id and the instant_clone_domain_account_id. You can go as crazy as you like and define each and every option as a parameter but I prefer a good base with the things that are changed the most often as parameters.

This is a sample of how I start the script, there is no feedback as the POST command doesn’t give any proper feedback if it ran well. I think the params are clear but you need to be careful to use a Relative Distinguished Name and not a normal Distinguished Name (the DC = parts are missing as you can see). For datastores you need to always need to use an array.

D:\GIT\Various_Scripts\Horizon_Rest_create_Desktop_Pool.ps1 -Credentials $creds -ConnectionServerURL https://pod1cbr1.loft.lab -jsonfile 'D:\homelab\new-pool-rest.json' -vCenterURL pod1vcr1.loft.lab -DataCenterName "Datacenter_Loft" -ClusterName "Dell 620" -BaseVMName "W21h1-2021-11-05-13-00" -BaseSnapShotName "Created by Packer" -DatastoreNames ("vdi-200","vdi-500") -VMFolderPath "/Datacenter_Loft/vm" -DesktopPoolName "Rest_Pool_demo" -DesktopPoolDisplayName "Rest Display name" -DesktopPoolDescription "rest description" -namingmethod "Restdemo{n:fixed=2}" -ADOUrdn "OU=Pool01,OU=VDI,OU=Pod1,OU=VMware,OU=EUC"

this gives this result:

Now the script itself, I am still using the default rest functions and only a slight bit of error handling for checking if the json exists and importing it. For the rest it’s a list of api calls that you (partially) have seen before in other scripts. The datastoressobjects array is filled with separate objects per datastore. The json is converted to a regular array at the beginning so it’s very easy to replace all variables that need replacing. To convert the object to a usable json file you need to change the max depth as this is default only 2 an that’s not enough for this json file. I set it to 100 just to keep things easy. If you want to download the script I would recommend grabbing it from Github.

In a future blog post I will cover adding different VM Networks to the desktop pool. With this json file the default nic of the Golden Image is used.

<#
    .SYNOPSIS
    Creates a new Golden Image to a Desktop Pool

    .DESCRIPTION
    This script uses the Horizon rest api's to create a new VMware Horizon Desktop Pool

    .EXAMPLE
    Horizon_Rest_create_Desktop_Pool.ps1 -Credentials $creds -ConnectionServerURL https://pod1cbr1.loft.lab -jsonfile 'D:\homelab\new-pool-rest.json' -vCenterURL pod1vcr1.loft.lab -DataCenterName "Datacenter_Loft" -ClusterName "Dell 620" -BaseVMName "W21h1-2021-11-05-13-00" -BaseSnapShotName "Created by Packer" -DatastoreNames  ("vdi-200","vdi-500") -VMFolderPath "/Datacenter_Loft/vm" -DesktopPoolName "Rest_Pool_demo2" -DesktopPoolDisplayName "Rest DIsplay name" -DesktopPoolDescription "rest description" -namingmethod "Rest-{n:fixed=2}" -ADOUrdn "OU=Pool01,OU=VDI,OU=Pod1,OU=VMware,OU=EUC"

    .PARAMETER Credential
    Mandatory: No
    Type: PSCredential
    Object with credentials for the connection server with domain\username and password. If not supplied the script will ask for user and password.

    .PARAMETER ConnectionServerURL
    Mandatory: Yes
    Default: String
    URL of the connection server to connect to

    .PARAMETER vCenterURL
    Mandatory: Yes
    Username of the user to look for

    .PARAMETER DataCenterName
    Mandatory: Yes
    Name of the datacenter

    .PARAMETER BaseVMName
    Mandatory: Yes
    Name of the Golden Image VM

    .PARAMETER BaseSnapShotName
    Mandatory: Yes
    Name of the Golden Image Snapshot

    .PARAMETER DesktopPoolName
    Mandatory: Yes
    Name of the Desktop Pool to ctreate

    .PARAMETER jsonfile
    Mandatory: Yes
    Full path to the JSON file to use as base

    .PARAMETER ClusterName
    Mandatory: Yes
    Name of the vCenter Cluster to place the vm's in

    .PARAMETER DatastoreNames
    Mandatory: Yes
    Array of names of the datastores to use

    .PARAMETER VMFolderPath
    Mandatory: Yes
    Path to the folder where the folder with pool vm's will be placed including the datacenter with forward slashes so /datacenter/folder

    .PARAMETER DesktopPoolDisplayName
    Mandatory: Yes
    Display name of the desktop pool

    .PARAMETER DesktopPoolDescription
    Mandatory: Yes
    Description of the desktop pool

    .PARAMETER NamingMethod
    Mandatory: Yes
    Naming method of the vm's

    .PARAMETER ADOUrdn
    Mandatory: Yes
    Relative Distinguished Name for the OU where the vm's will be placed

    .NOTES
    Minimum required version: VMware Horizon 8 2111
    Created by: Wouter Kursten
    First version: 08-12-2021

    .COMPONENT
    Powershell Core
#>

<#
Copyright © 2021 Wouter Kursten
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, 
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#>

[CmdletBinding()]
param (
    [Parameter(Mandatory=$false,
    HelpMessage='Credential object as domain\username with password' )]
    [PSCredential] $Credentials,

    [Parameter(Mandatory=$true,  HelpMessage='FQDN of the connectionserver' )]
    [ValidateNotNullOrEmpty()]
    [string] $ConnectionServerURL,

    [parameter(Mandatory = $true,
    HelpMessage = "URL of the vCenter to look in i.e. https://vcenter.domain.lab")]
    [ValidateNotNullOrEmpty()]
    [string]$vCenterURL,

    [parameter(Mandatory = $true,
    HelpMessage = "Name of the Datacenter to look in.")]
    [ValidateNotNullOrEmpty()]
    [string]$DataCenterName,

    [parameter(Mandatory = $true,
    HelpMessage = "Name of the Golden Image VM.")]
    [ValidateNotNullOrEmpty()]
    [string]$BaseVMName,

    [parameter(Mandatory = $true,
    HelpMessage = "Name of the Snapshot to use for the Golden Image.")]
    [ValidateNotNullOrEmpty()]
    [string]$BaseSnapShotName,

    [parameter(Mandatory = $true,
    HelpMessage = "Name of the Desktop Pool.")]
    [ValidateNotNullOrEmpty()]
    [string]$DesktopPoolName,

    [parameter(Mandatory = $true,
    HelpMessage = "Display Name of the Desktop Pool.")]
    [ValidateNotNullOrEmpty()]
    [string]$DesktopPoolDisplayName,

    [parameter(Mandatory = $true,
    HelpMessage = "Description of the Desktop Pool.")]
    [ValidateNotNullOrEmpty()]
    [string]$DesktopPoolDescription,

    [parameter(Mandatory = $true,
    HelpMessage = "Name of the cluster where the Desktop Pool will be placed.")]
    [ValidateNotNullOrEmpty()]
    [string]$ClusterName,

    [parameter(Mandatory = $true,
    HelpMessage = "Array of names for the datastores where the Desktop will be placed.")]
    [ValidateNotNullOrEmpty()]
    [array]$DatastoreNames,

    [parameter(Mandatory = $true,
    HelpMessage = "Path to the folder where the folder for the Desktop Pool will be placed i.e. /Datacenter_Loft/vm")]
    [ValidateNotNullOrEmpty()]
    [string]$VMFolderPath,

    [parameter(Mandatory = $true,
    HelpMessage = "Relative Distinguished Name for the OU where the vm's will be placed i.e. OU=Pool01,OU=VDI,OU=Pod1,OU=VMware,OU=EUC")]
    [ValidateNotNullOrEmpty()]
    [string]$ADOUrdn,

    [parameter(Mandatory = $true,
    HelpMessage = "Naming method for the VDI machines.")]
    [ValidateNotNullOrEmpty()]
    [string]$NamingMethod,

    [parameter(Mandatory = $true,
    HelpMessage = "Full path to the Json with Desktop Pool details.")]
    [ValidateNotNullOrEmpty()]
    [string]$jsonfile
)

try{
    test-path $jsonfile  | out-null
}
catch{
    throw "Json file not found"
}
try{
    $sourcejson = get-content $jsonfile | ConvertFrom-Json
}
catch{
    throw "Error importing json file"
}

if($Credentials){
    $username=($credentials.username).split("\")[1]
    $domain=($credentials.username).split("\")[0]
    $password=$credentials.password
}
else{
    $credentials = Get-Credential
    $username=($credentials.username).split("\")[1]
    $domain=($credentials.username).split("\")[0]
    $password=$credentials.password
}

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) 
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

function Get-HRHeader(){
    param($accessToken)
    return @{
        'Authorization' = 'Bearer ' + $($accessToken.access_token)
        'Content-Type' = "application/json"
    }
}
function Open-HRConnection(){
    param(
        [string] $username,
        [string] $password,
        [string] $domain,
        [string] $url
    )

    $Credentials = New-Object psobject -Property @{
        username = $username
        password = $password
        domain = $domain
    }

    return invoke-restmethod -Method Post -uri "$ConnectionServerURL/rest/login" -ContentType "application/json" -Body ($Credentials | ConvertTo-Json)
}
function Close-HRConnection(){
    param(
        $accessToken,
        $ConnectionServerURL
    )
    return Invoke-RestMethod -Method post -uri "$ConnectionServerURL/rest/logout" -ContentType "application/json" -Body ($accessToken | ConvertTo-Json)
}

try{
    $accessToken = Open-HRConnection -username $username -password $UnsecurePassword -domain $Domain -url $ConnectionServerURL
}
catch{
    throw "Error Connecting: $_"
}

$vCenters = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/monitor/v2/virtual-centers" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$vcenterid = ($vCenters | where-object {$_.name -like "*$vCenterURL*"}).id
$datacenters = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/external/v1/datacenters?vcenter_id=$vcenterid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$datacenterid = ($datacenters | where-object {$_.name -eq $DataCenterName}).id
$clusters = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/external/v1/hosts-or-clusters?datacenter_id=$datacenterid&vcenter_id=$vcenterid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$clusterid = ($clusters | where-object {$_.details.name -eq $ClusterName}).id
$datastores = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/external/v1/datastores?host_or_cluster_id=$clusterid&vcenter_id=$vcenterid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$datastoreobjects = @()
foreach ($datastoreName in $DatastoreNames){
    $datastoreid = ($datastores | where-object {$_.name -eq $datastoreName}).id
    [PSCustomObject]$dsobject=[ordered]@{
        datastore_id = $datastoreid
    }
    $datastoreobjects+=$dsobject

}
$resourcepools = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/external/v1/resource-pools?host_or_cluster_id=$clusterid&vcenter_id=$vcenterid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$resourcepoolid = $resourcepools[0].id
$vmfolders = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/external/v1/vm-folders?datacenter_id=$datacenterid&vcenter_id=$vcenterid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$vmfolderid = ($vmfolders | where-object {$_.path -eq $VMFolderPath}).id
$basevms = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/external/v1/base-vms?datacenter_id=$datacenterid&filter_incompatible_vms=false&vcenter_id=$vcenterid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$basevmid = ($basevms | where-object {$_.name -eq $baseVMName}).id
$basesnapshots = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/external/v1/base-snapshots?base_vm_id=$basevmid&vcenter_id=$vcenterid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$basesnapshotid = ($basesnapshots | where-object {$_.name -eq $BaseSnapShotName}).id
$sourcejson.provisioning_settings.base_snapshot_id = $basesnapshotid
$sourcejson.provisioning_settings.datacenter_id = $datacenterid
$sourcejson.provisioning_settings.host_or_cluster_id = $clusterid
$sourcejson.provisioning_settings.parent_vm_id = $basevmid
$sourcejson.provisioning_settings.vm_folder_id = $vmfolderid
$sourcejson.provisioning_settings.resource_pool_id = $resourcepoolid
$sourcejson.vcenter_id = $vcenterid
$sourcejson.storage_settings.datastores = $datastoreobjects
$sourcejson.name = $DesktopPoolName
$sourcejson.display_name = $DesktopPoolDisplayName
$sourcejson.description = $DesktopPoolDescription
$sourcejson.pattern_naming_settings.naming_pattern = $namingmethod

$json = $sourcejson | convertto-json -Depth 100

try{
    Invoke-RestMethod -Method Post -uri "$ConnectionServerURL/rest/inventory/v1/desktop-pools" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) -body $json
}
catch{
    throw $_
}

 

 

Horizon 8 2111 GA: What’s new in the rest api’s?

So just found out that Horizon 8 2111 dropped today and there have been some welcome changes to the rest api’s. Luckily VMware does have these covered by now in THIS kb article.

In short these are the changes:

Inventory : Desktop Pools
Create desktop pool
Update desktop pool
Delete desktop pool
v5 version of List
v5 version of Get
Inventory : Desktop Actions
Validate Installed Applications
Validate VM Names Info
Resume Task on Desktop pool
Pause task on Desktop pool
Inventory : Farms
v3 version of List
v3 version of Get
v2 version of Create
v2 version of Update
Inventory : Farm Actions
Add RDS servers to farm
Remove RDS servers from farm
Schedule Maintenance (and image management schedule maintenance)
Cancel Schedule Maintenance
Validate Installed Applications
Inventory : Global Application Entitlements
v2 version of List
v2 version of Get
Create Global Application Entitlements
Update Global Application Entitlements
Delete Global Application Entitlements
List Compatible Backup Global Application Entitlements
Inventory : Global Desktop Entitlements
version of List
v2 version of Get
Create Global Desktop Entitlements
Update Global Desktop Entitlements
Delete Global Desktop Entitlements
List Compatible Backup Global Desktop Entitlements
Inventory : Global Sessions
List
Disconnect
Logoff
Reset
Restart
Send Message

so finally we’re able to create desktop pools using REST and to push a new image to rds farms. I will make sure to update the Python module ®Soon and create some blog posts on the new options.

[HorizonAPI]Powershell Script to push a new Desktop image using the REST api.

I already blogged about pushing a new image using the Python module for Horizon but I decided it was time to also have a reusable script that is able to push a new image using powershell and the rest api for Horizon. The script that I created has 10(!) arguments of which 6 are required:

  • ConnectionServerURL: https://server.domain.dom
  • vCenterURL: https://vcenter.domain.dom
  • DataCenterName: Name of the datacenter the source VM resides in
  • BaseVMName : name of the source VM
  • BaseSnapShotName: name of the source Snapshot
  • DesktopPoolName: name of the source Desktop Pool to apply the snapshot to

The datacenter name is required as that’s an requirement to grab the Source VM details.

The optional arguments are:

  • Credentials: PSCRedential object (get-credential for example) when not provided it will ask for user and password. The user should also contain the domain i.e. domain\user
  • StoponError: $true or $false depending on if you want to stop on errors, defaults to $true if not provided
  • logoff_policy: Optional WAIT_FOR_LOGOFF or FORCE_LOGOFF depending on the logoff policy you want
  • Scheduledtime: [DateTime] object in case you want to push for the future

The script itself was fairly easy to create, from the api explorer it was easy what id’s I needed and it was a matter of working back so I had all of them. In the end the hardest part was getting the scheduling to work. I used the (standard?) 10 digit epoch that most people use but it turns out that VMware wanted to schedule it very exactly in milliseconds! For the rest I used the well known functions for authentication but not my generic function for filtering or pagination as almost none of the api calls I use in this script support that.

<#
    .SYNOPSIS
    Pushes a new Golden Image to a Desktop Pool

    .DESCRIPTION
    This script uses the Horizon rest api's to push a new golden image to a VMware Horizon Desktop Pool

    .EXAMPLE
    .\Horizon_Rest_Push_Image.ps1 -ConnectionServerURL https://pod1cbr1.loft.lab -Credentials $creds -vCenterURL "https://pod1vcr1.loft.lab" -DataCenterName "Datacenter_Loft" -baseVMName "W21h1-2021-09-08-15-48" -BaseSnapShotName "Demo Snapshot" -DesktopPoolName "Pod01-Pool02"

    .PARAMETER Credential
    Mandatory: No
    Type: PSCredential
    Object with credentials for the connection server with domain\username and password. If not supplied the script will ask for user and password.

    .PARAMETER ConnectionServerURL
    Mandatory: Yes
    Default: String
    URL of the connection server to connect to

    .PARAMETER vCenterURL
    Mandatory: Yes
    Username of the user to look for

    .PARAMETER DataCenterName
    Mandatory: Yes
    Domain to look in

    .PARAMETER BaseVMName
    Mandatory: Yes
    Domain to look in

    .PARAMETER BaseSnapShotName
    Mandatory: Yes
    Domain to look in

    .PARAMETER DesktopPoolName
    Mandatory: Yes
    Domain to look in

    .PARAMETER StoponError
    Mandatory: No
    Boolean to stop on error or not

    .PARAMETER logoff_policy
    Mandatory: No
    String FORCE_LOGOFF or WAIT_FOR_LOGOFF to set the logoff policy.

    .PARAMETER Scheduledtime
    Mandatory: No
    Time to schedule the image push in [DateTime] format.

    .NOTES
    Minimum required version: VMware Horizon 8 2012
    Created by: Wouter Kursten
    First version: 03-11-2021

    .COMPONENT
    Powershell Core
#>

[CmdletBinding()]
param (
    [Parameter(Mandatory=$false,
    HelpMessage='Credential object as domain\username with password' )]
    [PSCredential] $Credentials,

    [Parameter(Mandatory=$true,  HelpMessage='FQDN of the connectionserver' )]
    [ValidateNotNullOrEmpty()]
    [string] $ConnectionServerURL,

    [parameter(Mandatory = $true,
    HelpMessage = "URL of the vCenter to look in i.e. https://vcenter.domain.lab")]
    [ValidateNotNullOrEmpty()]
    [string]$vCenterURL,

    [parameter(Mandatory = $true,
    HelpMessage = "Name of the Datacenter to look in.")]
    [ValidateNotNullOrEmpty()]
    [string]$DataCenterName,

    [parameter(Mandatory = $true,
    HelpMessage = "Name of the Golden Image VM.")]
    [ValidateNotNullOrEmpty()]
    [string]$BaseVMName,

    [parameter(Mandatory = $true,
    HelpMessage = "Name of the Snapshot to use for the Golden Image.")]
    [ValidateNotNullOrEmpty()]
    [string]$BaseSnapShotName,

    [parameter(Mandatory = $true,
    HelpMessage = "Name of the Desktop Pool.")]
    [ValidateNotNullOrEmpty()]
    [string]$DesktopPoolName,

    [parameter(Mandatory = $false,
    HelpMessage = "Name of the Desktop Pool.")]
    [ValidateNotNullOrEmpty()]
    [bool]$StoponError = $true,

    [parameter(Mandatory = $false,
    HelpMessage = "Name of the Desktop Pool.")]
    [ValidateSet('WAIT_FOR_LOGOFF','FORCE_LOGOFF', IgnoreCase = $false)]
    [string]$logoff_policy = "WAIT_FOR_LOGOFF",

    [parameter(Mandatory = $false,
    HelpMessage = "DateTime object for the moment of scheduling the image push.Defaults to immediately")]
    [datetime]$Scheduledtime
)
if($Credentials){
    $username=($credentials.username).split("\")[1]
    $domain=($credentials.username).split("\")[0]
    $password=$credentials.password
}
else{
    $credentials = Get-Credential
    $username=($credentials.username).split("\")[1]
    $domain=($credentials.username).split("\")[0]
    $password=$credentials.password
}

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password) 
$UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

function Get-HRHeader(){
    param($accessToken)
    return @{
        'Authorization' = 'Bearer ' + $($accessToken.access_token)
        'Content-Type' = "application/json"
    }
}
function Open-HRConnection(){
    param(
        [string] $username,
        [string] $password,
        [string] $domain,
        [string] $url
    )

    $Credentials = New-Object psobject -Property @{
        username = $username
        password = $password
        domain = $domain
    }

    return invoke-restmethod -Method Post -uri "$ConnectionServerURL/rest/login" -ContentType "application/json" -Body ($Credentials | ConvertTo-Json)
}
function Close-HRConnection(){
    param(
        $accessToken,
        $ConnectionServerURL
    )
    return Invoke-RestMethod -Method post -uri "$ConnectionServerURL/rest/logout" -ContentType "application/json" -Body ($accessToken | ConvertTo-Json)
}

try{
    $accessToken = Open-HRConnection -username $username -password $UnsecurePassword -domain $Domain -url $ConnectionServerURL
}
catch{
    throw "Error Connecting: $_"
}

$vCenters = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/monitor/v2/virtual-centers" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$vcenterid = ($vCenters | where-object {$_.name -like "*$vCenterURL*"}).id
$datacenters = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/external/v1/datacenters?vcenter_id=$vcenterid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$datacenterid = ($datacenters | where-object {$_.name -eq $DataCenterName}).id
$basevms = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/external/v1/base-vms?datacenter_id=$datacenterid&filter_incompatible_vms=false&vcenter_id=$vcenterid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$basevmid = ($basevms | where-object {$_.name -eq $baseVMName}).id
$basesnapshots = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/external/v1/base-snapshots?base_vm_id=$basevmid&vcenter_id=$vcenterid" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$basesnapshotid = ($basesnapshots | where-object {$_.name -eq $BaseSnapShotName}).id
$desktoppools = Invoke-RestMethod -Method Get -uri "$ConnectionServerURL/rest/inventory/v1/desktop-pools" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken)
$desktoppoolid = ($desktoppools | where-object {$_.name -eq $DesktopPoolName}).id
$startdate = (get-date -UFormat %s)
$datahashtable = [ordered]@{}
$datahashtable.add('logoff_policy',$logoff_policy)
$datahashtable.add('parent_vm_id',$basevmid)
$datahashtable.add('snapshot_id',$basesnapshotid)
if($Scheduledtime){
    $starttime = get-date $Scheduledtime
    $epoch = ([DateTimeOffset]$starttime).ToUnixTimeMilliseconds()
    $datahashtable.add('start_time',$epoch)
}

$datahashtable.add('stop_on_first_error',$StoponError)
$json = $datahashtable | convertto-json
Invoke-RestMethod -Method Post -uri "$ConnectionServerURL/rest/inventory/v1/desktop-pools/$desktoppoolid/action/schedule-push-image" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) -body $json

I use it like this for example:

D:\GIT\Various_Scripts\Horizon_Rest_Push_Image.ps1 -ConnectionServerURL https://pod1cbr1.loft.lab -vCenterURL "https://pod1vcr1.loft.lab" -DataCenterName "Datacenter_Loft" -baseVMName "W21h1-2021-09-08-15-48" -BaseSnapShotName "Demo Snapshot" -DesktopPoolName "Pod01-Pool01" -logoff_policy WAIT_FOR_LOGOFF -StoponError $true -Scheduledtime ((get-date).AddMinutes(75))

Except for the question for username and password (in this case) there’s no response

and the push image is scheduled 75 minutes in the future

As always the script itself is also available at Github HERE.

Next time I’ll add more error handling and update the script to also push images to RDS farms 🙂