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.
So besides the cpu/memory changes we obviously also have something called selective_push_image. This has to do with the added functionality of pushing a secondary image from Horizon 2111. While the example shows it as true the data model makes clear that it is not required and defaults to false. The array of machine_ids reflects the list of machines where the secondary image has to be applied.
compute_profile_num_cores_per_socket integer($int32)
example: 1
minimum: 1
exclusiveMinimum: false
exclusiveMaximum: false
Indicates the number of cores per socket for the CPU in the compute profile to be configured on clones.
If set, both compute_profile_num_cpus and compute_profile_ram_mb need to be set.
compute_profile_num_cpus integer($int32)
example: 4
minimum: 1
exclusiveMinimum: false
exclusiveMaximum: false
Indicates the number of CPUs in the compute profile to be configured on clones.
If set, this must be a multiple of compute_profile_num_cores_per_socket.
compute_profile_ram_mb integer($int32)
example: 4096
minimum: 1024
exclusiveMinimum: false
exclusiveMaximum: false
Indicates the RAM in MB in the compute profile to be configured on clones.
machine_ids [
example: List [ "816d44cb-b486-3c97-adcb-cf3806d53657", "414927f3-1a3b-3e4c-81b3-d39602f634dc" ]
Set of machines from the desktop pool on which the new image is to be applied. This can be set when selective_push_image is set to true.
selective_push_image boolean
example: true
Indicates whether selective push image is to be applied. If set to true, the new image will be applied to specified machine_ids in the desktop pool. The image published with this option will be held as a pending image, unless it is promoted or cancelled. The default value is false.
To be able to use this I have updated my previous image deployment script for Horizon 2206.
New arguments are:
AddVirtualTPM
Boolean to add a virtual TPM or not
SecondaryImage
Boolean to define the image as secondary (required if you also supply machine_ids)
Machine_Ids
Array with machine_ids to supply the secondary image to
CoresPerSocket
Int with # of Cores per Socket
CPUs
Int for total number of cpus
MemoryinMB
Memory in mb so 4096 or 6192 for example
<#
.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.
.PARAMETER AddVirtualTPM
Mandatory: No
Default: $False
Boolean FORCE_LOGOFF or WAIT_FOR_LOGOFF to set the logoff policy.
.PARAMETER SecondaryImage
Mandatory: No (Yes if machine_ids is supplied)
Default: $False
Boolean FORCE_LOGOFF or WAIT_FOR_LOGOFF to set the logoff policy.
.PARAMETER Machine_Ids
Mandatory: No
Array Array of Machine_ids to apply the secondary image to.
.PARAMETER CoresPerSocket
Mandatory: No (unless CPUs or MemoryinMB is supplies)
Int Amount of cores per socket.
.PARAMETER CPUs
Mandatory: No (unless MemoryinMB or CoresPerSocket is supplies)
Int Total number of cores.
.PARAMETER MemoryinMB
Mandatory: No (unless CPUs or CoresPerSocket is supplies)
Int New memory in MB
.NOTES
Minimum required version: VMware Horizon 8 2206
Created by: Wouter Kursten
First version: 03-11-2021
Changes: 05-09-2022 - Added resizing of cpu/memory
- Added secondary image functionality
- Added option to add Virtual TPM
.COMPONENT
Powershell Core
#>
[CmdletBinding(DefaultParameterSetName = 'Generic')]
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 = "True or false for stop on error.")]
[ValidateNotNullOrEmpty()]
[bool]$StoponError = $true,
[parameter(Mandatory = $false,
HelpMessage = "Use WAIT_FOR_LOGOFF or FORCE_LOGOFF.")]
[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,
[parameter(Mandatory = $false,
HelpMessage = "Bool for adding a Virtual TPM or not.")]
[ValidateNotNullOrEmpty()]
[bool]$AddVirtualTPM = $False,
[parameter(Mandatory = $false,
HelpMessage = "True or false to set this image as secondary image.")]
[ValidateNotNullOrEmpty()]
[bool]$SecondaryImage = $False,
[parameter(Mandatory = $false,
HelpMessage = "Array of machine_ids to apply the secondary image to.")]
[ValidateNotNullOrEmpty()]
[array]$Machine_Ids,
[parameter(Mandatory = $false,
HelpMessage = "New Number of cores per socket.")]
[ValidateNotNullOrEmpty()]
[int]$CoresPerSocket,
[parameter(Mandatory = $false,
HelpMessage = "New Number of CPU's.")]
[ValidateNotNullOrEmpty()]
[int]$CPUs,
[parameter(Mandatory = $false,
HelpMessage = "New amount of memory in MB.")]
[ValidateNotNullOrEmpty()]
[int]$MemoryinMB
)
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)
}
if($CPUs -AND $CoresPerSocket -AND $MemoryinMB){
$resize = $true
}
elseif($CPUs -OR $CoresPerSocket -OR $MemoryinMB){
throw "If either CPUs, CoresPerSOcket or MemoryinGB is supplied, all must be supplied."
}
else{
$resize = $false
}
if($Machine_Ids -AND !($SecondaryImage)){
throw "If either Machine_Ids is supplied SecondaryImage also needs to be supplied."
}
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
$datahashtable = [ordered]@{}
$datahashtable.add('add_virtual_tpm',$AddVirtualTPM)
if($resize){
$datahashtable.add('compute_profile_num_cores_per_socket',$CoresPerSocket)
$datahashtable.add('compute_profile_num_cpus',$CPUs)
$datahashtable.add('compute_profile_ram_mb',$MemoryinMB)
}
$datahashtable.add('logoff_policy',$logoff_policy)
if($Machine_Ids){
$datahashtable.add('machine_ids',$Machine_Ids)
}
$datahashtable.add('parent_vm_id',$basevmid)
if($SecondaryImage){
$datahashtable.add('selective_push_image',$SecondaryImage)
}
$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/v2/desktop-pools/$desktoppoolid/action/schedule-push-image" -ContentType "application/json" -Headers (Get-HRHeader -accessToken $accessToken) -body $json
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.
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.
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
For those of you who haven’t seen my demo last week at the VMUG EUC day I have created a new script that will push a new Golden Image to a RDS farm. The same API call can also be used to schedule a recurring maintenance but that will have to wait for a future post.
What you need to run it are the following parameters:
-Credentials: credentials object from get-credential
-ConnectionServerURL: Full url to the connection server https://pod1cbr01.loft.lab for example
-vCenterURL : Full url to the vCenter Server: https://pod1vcr1.loft.lab
-DataCenterName : name of the Datacenter in vCenter
-BaseVMName : VM name of the new golden image
-BaseSnapShotName : name of the snapshot to be used
-FarmName : name of the RDS farm to push the image to
-StoponError : Boolean $True or $False to stop on error or not. Defaults to $true
-logoff_policy : String in capitals to wait for the users to logoff (WAIT_FOR_LOGOFF) or to forcefully log them off (FORCE_LOGOFF). Defaults to WAIT_FOR_LOGOFF
-Scheduledtime : datetime object for the time to schedule the image push. If not provided it will push the image immediately.
In my Lab I have this RDS Farm:
The last Image push actually failed
And It’s using this Golden Image with the Created by Packer Snapshot
With the following command I will push the new image:
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.
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.
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.
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.
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.
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
A while ago Robin Stolpe (Twitter) asked me if it was possible to find what machines a user is assigned to in a Horizon environment. To answer this I first started messing with the soap api’s and had a really hard time to filter for the user id with the various machine related queries. When looking for the assignedUser property this was no problem but this has been deprecated and replaced by assignedUsers because of the added functionality for assigning multiple users to a machine. Instead of becoming too frustrated I decided to switch paths and user Powershell with the rest api’s.
TLDR: I have defined a broadly usable function for just about all Horizon REST GET api calls with or without filtering that also works for GET calls without any additions and for GET calls that require an Id for example. You can scroll down to the bottom to get that function and a script that uses it.
Warning: the sample code in the script & example function require PowerShell 7!
Filtering
One of the things I hadn’t done before with these was filtering and pagination in a more useful way than just writing the entire url out. VMware has a guide available for filtering that can be found here. This was a good way to get started but I found it easiest to skip the single searches entirely and always use the And or Or filtering types for chained filtering.
The method I am using to create the filter is to first define an ordered hashtable. Why ordered? The api calls require the Name/value pairs in a certain order and if you just add them to a regular hashtable this order will change.
$filterhashtable = [ordered]@{}
Next I add the first Name/value pair for the filtertype, this is either And or Or
$filterhashtable.add('type', 'And')
Next I add another pair with name filters and value an array. I could use .add again or just set the name like I do here:
$filterhashtable.filters = @()
The filters name array members again need to be ordered hashtable’s (as you can see I search for a user here)
For the pagination I needed the HAS_MORE_RECORDS property of the returned headers. If this is TRUE there are more records to be found, sadly this is not available in the classic invoke-restmethod from Powershell v5. With Powershell 7 you can add -ResponseHeadersVariable responseheader to store the headers in a variable called $responseheader. With this variable you can easily create a do while loop.
Please be advised that without some additional parameters this code isn’t usable yet, scroll down for something you can really use.
[sta_anchor id=”function” /]
The function
To combine the above 2 items I have created a function that can use all of the above but is also able to do regular get calls and get calls that require an id in the url.
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. /rest/external/v1/ad-users-or-groups' )]
[string] $RestMethod,
[Parameter(Mandatory=$true,
HelpMessage='Part after the url in the swagger UI i.e. /rest/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
}
As you can see there are several arguments:
ServerURL
This is the url to the connection server i.e. https://server.domain
Filters
An Array of ordered hashtables as you can find in the filtering paragraph
filtertype
Sets the filter type, this needs to be And or Or
PageSize
This is optional if you want to change from the default 500 results that I have set
RestMethod
This is the RestMethod that you can copy from the Swagger URL or API Explorer.
AccessToken
This is the accesstoken you get as a result when using open-hrconnection from previous samples to authenticate (see the sample script below)
Filteringandpagination
Add this argument to use the filtering and/or pagination options
Id
Use this for REST API Get calls where an Id is required in the URI
The script below (and available on Github here) aks for credentials if you don’t supply the object, connectionserver FQDN (no url needed), user and domain to search for and returns an array of machines the user is assigned to. It uses the default functions Andrew Morgan created a long time ago and my function to use the get methods.
<#
.SYNOPSIS
Retreives all machines a user is assigned to
.DESCRIPTION
This script uses the Horizon rest api's to query the Horizon database for all machines a user is assigned to.
.EXAMPLE
.\find_user_assigned_desktops.ps1 -Credential $creds -ConnectionServerFQDN pod2cbr1.loft.lab -UserName "User2"
.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 User
Mandatory: Yes
Username of the user to look for
.PARAMETER Domain
Mandatory: Yes
Domain to look in
.NOTES
Created by: Wouter Kursten
First version: 02-10-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 = "Username of the user to look for.")]
[string]$User = $false,
[parameter(Mandatory = $true,
HelpMessage = "Domain where the user object exists.")]
[string]$Domain = $false
)
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
}
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
$userfilters = @()
$userfilter= [ordered]@{}
$userfilter.add('type','Equals')
$userfilter.add('name','name')
$userfilter.add('value',$User)
$userfilters+=$userfilter
$domainfilter= [ordered]@{}
$domainfilter.add('type','Equals')
$domainfilter.add('name','domain')
$domainfilter.add('value',$Domain)
$userfilters+=$domainfilter
$userobject = Get-HorizonRestData -ServerURL $url -filteringandpagination -Filtertype "And" -filters $userfilters -RestMethod "/external/v1/ad-users-or-groups" -accessToken $accessToken
$machinefilters = @()
$machinefilter= [ordered]@{}
$machinefilter.add('type','Contains')
$machinefilter.add('name','user_ids')
$machinefilter.add('value',($userobject).id)
$machinefilters+=$machinefilter
$machines = Get-HorizonRestData -ServerURL $url -filteringandpagination -Filtertype "And" -filters $machinefilters -RestMethod "/inventory/v1/machines" -accessToken $accessToken
return $machines
I use it like this to only display the machine names
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here:
Cookie Policy