Removing faulty Horizon desktops using PowerCLI

So last week there where a couple of posts on vmtn about people wanting to automatically removing or refreshing faulty Horizon desktops. With faulty I mean desktops in Agent Unreachable or in error state or whatever status are available. Since this was something i had been investigating anyway I decided to make a script for it that had separate menu’s for the status the desktop needs to be and to pick the desktop to be deleted. The latter part can be rebuild to do all those desktops at once  in case something breaks pretty badly during a recompose of the pool.

The largest part of the script is for creating the menu’s. Since the amount of returned desktops is variable and names differ it’s not possible to use a static menu. Instead I have used a menu structure created by Roman Gelman and that can be found inside this script on github. The part that gets things done i have listed below. The $spec array doesn’t need to be created but it is required in the API call to remove the desktop, Powershell assumes everything true by default when it’s empty but it just has to be called otherwise you will get a big fat red error. To remove multiple desktops at once machine_deletemachines needs to be used with an array filled with desktop id’s and $spec.

$spec = New-Object VMware.Hv.machinedeletespec

$desktops=get-hvmachine -state $targetstate
foreach ($desktop in $desktops){
    $selectdesktop+= New-Object PSObject -Property @{"Name" = $
    "ID" = $;

$selectdesktop=write-menu -menu ($ -header "Select the desktop you want to remove"
$removedesktop=$desktops | where {$ -eq $selectdesktop}

try {
	$services1.machine.machine_delete($, $spec)
	#$services1.machine.machine_reset($, $spec)	
	write-host "$selectdesktop will be marked for deletion" -ForegroundColor Green
catch {
	write-host "Error deleting $selectdesktop" -ForegroundColor Red

As always the complete script can be found at Github where it will also be updated. This is how it looks in the end:


After the comment below I decided to create the script to delete all desktops in a certain state. It’s a variation of the script above, just a bit shorter. Again it can be found on Github. Please be aware that due to a limitation in get-hvmachine both these scripts will only handle 1000 desktops at a time. It is safe to just repeat the script to do the rest.

Bookmark the permalink.

Comments are closed.