VMware Horizon Community
sureshasai
Enthusiast
Enthusiast
Jump to solution

Script for Horizon problem VDI machines

The Script attached below having some error in Line 57 and 59.

####################################

 


$cs = 'Connection serverl' #Horizon Connection Server
$csUser= 'Username' #User account to connect to Connection Server
$csPassword = 'Password' #Password for user to connect to Connection Server
$csDomain = 'Domain' #Domain for user to connect to Connection Server

$vc = 'Vcenter name' #vCenter Server
$vcUser = 'User name' #User account to connect to vCenter Server
$vcPassword = 'Password' #Password for user to connect to vCenter Server

$baseStates = @('PROVISIONING_ERROR',
'ERROR',
'Already_used',
'AGENT_UNREACHABLE',
'AGENT_ERR_STARTUP_IN_PROGRESS',
'AGENT_ERR_DISABLED',
'AGENT_ERR_INVALID_IP',
'AGENT_ERR_NEED_REBOOT',
'AGENT_ERR_PROTOCOL_FAILURE',
'AGENT_ERR_DOMAIN_FAILURE',
'AGENT_CONFIG_ERROR',
'UNKNOWN')

#endregion variables

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

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

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

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

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

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

foreach ($ProblemVM in $ProblemVMs) {


$VM = Get-VM -Name $ProblemVMs.Base.Name

# --- Reboot each of the Problem VMs ---
Restart-VMGuest -VM $VM

# Add -WhatIf to see what would happen without actually carrying out the action.
}
}
Write-Output "", "Disconnect from Connection Server."
Disconnect-HVServer -Server $cs
} else {
Write-Output "", "Failed to login in to Connection Server."
pause
}

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

##################################################################

Error message 

 

 

Get-VM : 9/4/2021 3:02:02 PM Get-VM VM with name 'vm-hq-incl-010' was not found using
the specified filter(s).
At line:56 char:7
+ $VM = Get-VM -Name $ProblemVMs.Base.Name
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-VM], VimException
+ FullyQualifiedErrorId : Core_OutputHelper_WriteNotFoundError,VMware.VimAutomatio
n.ViCore.Cmdlets.Commands.GetVM

Restart-VMGuest : Cannot validate argument on parameter 'VM'. The argument is null or
empty. Provide an argument that is not null or empty, and then try the command again.
At line:58 char:21
+ Restart-VMGuest -VM $VM
+ ~~~
+ CategoryInfo : InvalidData: (:) [Restart-VMGuest], ParameterBindingVali
dationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,VMware.VimAutomation.Vi
Core.Cmdlets.Commands.RestartVmGuest

Labels (1)
Tags (1)
Reply
0 Kudos
2 Solutions

Accepted Solutions
jhol5
Enthusiast
Enthusiast
Jump to solution

If the VM is 'missing' in vCenter "$VM = Get-VM -Name $ProblemVMs.Base.Name" will return null, which causes "Restart-VMGuest -VM $VM" to error out.

 

You can add "-ErrorAction SilentlyContinue" to the Restart-VMGuest command, "Restart-VMGuest -VM $VM -ErrorAction SilentlyContinue", but a better thing would be to test if $VM is null or not.

View solution in original post

Reply
0 Kudos
jhol5
Enthusiast
Enthusiast
Jump to solution

Here is my modified version of the script found in this blog post.

The difference is that I pass in "VICredentialStoreItem" xml files instead of storing them in the script and I test to see if the VM state is powered on before rebooting it. The reboot command is basically the shut down command and then the start command so if it can't shut it down, it will also error out and won't attempt to start the VM if it's in a powered off state.

function Reboot-HVProblemMachines {
    [CmdletBinding()]
	Param(
        [Parameter(Mandatory=$true)]
        [String]$HorizonCredStore,
        [Parameter(Mandatory=$true)]
        [String]$vCenterCredStore
	)

<#
	.SYNOPSIS
	Reboots problem VM's in the VMware Environment.
	.DESCRIPTION
	This function restarts all problem VM's in the VMware Environment by connecting to a Horizon Connection server querying the problem VM's, then connects to vCenter to gracefully restart the VM(s).
	The original script is at the end of this page, above the summary: https://blogs.vmware.com/euc/2017/01/vmware-horizon-7-powercli-6-5.html. I have removed the reboot and need to connect to vCenter and changed how the script authenticates to the View Admin server.
	.EXAMPLE
		Reboot-HVProblemMachines -HorizonCredStore 'C:\Scripts\credfileview.xml' -vCenterCredStore C:\Scripts\credfilevcenter.xml -HorizonServer 'hva.mydomain.com' -vCenterServer 'vcenter.mydomain.com'
	.NOTES
		Version                     : 1.0.2
		Dependencies                : Make sure to have loaded VMware.HvHelper module loaded on your machine, see: https://blogs.vmware.com/euc/2017/01/vmware-horizon-7-powercli-6-5.html. Also it's state later in the script but you need to run "New-VICredentialStoreItem -host <vcenter server IP address> -user <username> -password <password> -file C:\Scripts\credfilevcenter.xml" to generate a secure encryped credental file first.
		===Tested Against Environment====
		Horizon View Server Version : 7.4.0
        vCenter                     : 6.5.0
		PowerCLI Version            : PowerCLI 6.5, PowerCLI 6.5.1
		PowerShell Version          : 5.0
#>
	# --- Import the PowerCLI Modules required ---
    Import-Module VMware.VimAutomation.HorizonView
    Import-Module VMware.VimAutomation.Core
    Import-Module VMware.Hv.Helper

###################################################################
#                    Variables                                    #
###################################################################

    #Import Credentail Files New-VICredentialStoreItem -host <vcenter server IP address> -user <username> -password <password> -file C:\Scripts\credfilevcenter.xml
    $hvUser = Get-VICredentialStoreItem -File $HorizonCredStore
    $viUser = Get-VICredentialStoreItem -File $vCenterCredStore

    $baseStates = @(
        'PROVISIONING_ERROR',
        'ERROR',
        'AGENT_UNREACHABLE',
        'AGENT_ERR_STARTUP_IN_PROGRESS',
        'AGENT_ERR_DISABLED',
        'AGENT_ERR_INVALID_IP',
        'AGENT_ERR_NEED_REBOOT',
        'AGENT_ERR_PROTOCOL_FAILURE',
        'AGENT_ERR_DOMAIN_FAILURE',
        'AGENT_CONFIG_ERROR',
        'UNKNOWN'
    )

###################################################################
#                    Initialize                                   #
###################################################################
    # --- Connect to Horizon Connection Server API Service ---
    $hvServer1 = Connect-HVServer -Server $hvUser.Host -User $hvUser.User -Password $hvUser.Password
    Connect-VIServer -Server $viUser.Host -User $viUser.User -Password $viUser.Password

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

###################################################################
#                    Main                                         #
###################################################################
    if ($Services1) {
        foreach ($baseState in $baseStates) {
            # --- Get a list of VMs in this state ---
            $ProblemVMs = Get-HVMachineSummary -State $baseState -SuppressInfo $true
            
            foreach ($ProblemVM in $ProblemVMs) {
                $vm = Get-VM -Name $ProblemVM.Base.Name
                if($vm.PowerState -eq 'PoweredOn') { 
                    Restart-VMGuest -VM $vm | Out-Null
                    Write-Host ($ProblemVM.Base.Name + ' has started the reboot process.')
                }
                else { Write-Warning ($ProblemVM.Base.Name + ' is not powered on.') }
            }
        }
        
        # --- Disconnect from View Admin ---
        Disconnect-HVServer -Server $hvUser.Host -Confirm:$false | Out-Null
        Disconnect-VIServer -Server $viUser.Host -Confirm:$false | Out-Null
    } else {
        Write-Output "", "Failed to login in to server."
    }
#endregion main
}

 

View solution in original post

2 Replies
jhol5
Enthusiast
Enthusiast
Jump to solution

If the VM is 'missing' in vCenter "$VM = Get-VM -Name $ProblemVMs.Base.Name" will return null, which causes "Restart-VMGuest -VM $VM" to error out.

 

You can add "-ErrorAction SilentlyContinue" to the Restart-VMGuest command, "Restart-VMGuest -VM $VM -ErrorAction SilentlyContinue", but a better thing would be to test if $VM is null or not.

Reply
0 Kudos
jhol5
Enthusiast
Enthusiast
Jump to solution

Here is my modified version of the script found in this blog post.

The difference is that I pass in "VICredentialStoreItem" xml files instead of storing them in the script and I test to see if the VM state is powered on before rebooting it. The reboot command is basically the shut down command and then the start command so if it can't shut it down, it will also error out and won't attempt to start the VM if it's in a powered off state.

function Reboot-HVProblemMachines {
    [CmdletBinding()]
	Param(
        [Parameter(Mandatory=$true)]
        [String]$HorizonCredStore,
        [Parameter(Mandatory=$true)]
        [String]$vCenterCredStore
	)

<#
	.SYNOPSIS
	Reboots problem VM's in the VMware Environment.
	.DESCRIPTION
	This function restarts all problem VM's in the VMware Environment by connecting to a Horizon Connection server querying the problem VM's, then connects to vCenter to gracefully restart the VM(s).
	The original script is at the end of this page, above the summary: https://blogs.vmware.com/euc/2017/01/vmware-horizon-7-powercli-6-5.html. I have removed the reboot and need to connect to vCenter and changed how the script authenticates to the View Admin server.
	.EXAMPLE
		Reboot-HVProblemMachines -HorizonCredStore 'C:\Scripts\credfileview.xml' -vCenterCredStore C:\Scripts\credfilevcenter.xml -HorizonServer 'hva.mydomain.com' -vCenterServer 'vcenter.mydomain.com'
	.NOTES
		Version                     : 1.0.2
		Dependencies                : Make sure to have loaded VMware.HvHelper module loaded on your machine, see: https://blogs.vmware.com/euc/2017/01/vmware-horizon-7-powercli-6-5.html. Also it's state later in the script but you need to run "New-VICredentialStoreItem -host <vcenter server IP address> -user <username> -password <password> -file C:\Scripts\credfilevcenter.xml" to generate a secure encryped credental file first.
		===Tested Against Environment====
		Horizon View Server Version : 7.4.0
        vCenter                     : 6.5.0
		PowerCLI Version            : PowerCLI 6.5, PowerCLI 6.5.1
		PowerShell Version          : 5.0
#>
	# --- Import the PowerCLI Modules required ---
    Import-Module VMware.VimAutomation.HorizonView
    Import-Module VMware.VimAutomation.Core
    Import-Module VMware.Hv.Helper

###################################################################
#                    Variables                                    #
###################################################################

    #Import Credentail Files New-VICredentialStoreItem -host <vcenter server IP address> -user <username> -password <password> -file C:\Scripts\credfilevcenter.xml
    $hvUser = Get-VICredentialStoreItem -File $HorizonCredStore
    $viUser = Get-VICredentialStoreItem -File $vCenterCredStore

    $baseStates = @(
        'PROVISIONING_ERROR',
        'ERROR',
        'AGENT_UNREACHABLE',
        'AGENT_ERR_STARTUP_IN_PROGRESS',
        'AGENT_ERR_DISABLED',
        'AGENT_ERR_INVALID_IP',
        'AGENT_ERR_NEED_REBOOT',
        'AGENT_ERR_PROTOCOL_FAILURE',
        'AGENT_ERR_DOMAIN_FAILURE',
        'AGENT_CONFIG_ERROR',
        'UNKNOWN'
    )

###################################################################
#                    Initialize                                   #
###################################################################
    # --- Connect to Horizon Connection Server API Service ---
    $hvServer1 = Connect-HVServer -Server $hvUser.Host -User $hvUser.User -Password $hvUser.Password
    Connect-VIServer -Server $viUser.Host -User $viUser.User -Password $viUser.Password

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

###################################################################
#                    Main                                         #
###################################################################
    if ($Services1) {
        foreach ($baseState in $baseStates) {
            # --- Get a list of VMs in this state ---
            $ProblemVMs = Get-HVMachineSummary -State $baseState -SuppressInfo $true
            
            foreach ($ProblemVM in $ProblemVMs) {
                $vm = Get-VM -Name $ProblemVM.Base.Name
                if($vm.PowerState -eq 'PoweredOn') { 
                    Restart-VMGuest -VM $vm | Out-Null
                    Write-Host ($ProblemVM.Base.Name + ' has started the reboot process.')
                }
                else { Write-Warning ($ProblemVM.Base.Name + ' is not powered on.') }
            }
        }
        
        # --- Disconnect from View Admin ---
        Disconnect-HVServer -Server $hvUser.Host -Confirm:$false | Out-Null
        Disconnect-VIServer -Server $viUser.Host -Confirm:$false | Out-Null
    } else {
        Write-Output "", "Failed to login in to server."
    }
#endregion main
}