Categories
Uncategorized

Script for automating desktop logoffs in Horizon.

This script will let users know that there desktop will restart after 3 days if they don’t logout. It checks after 3 days and anyone who’s session is less than 5 days old won’t be restarted and everyone else will.

This requires the AD powershell module that gets installed with the AD RSAT tools and vmware hv helper module

https://github.com/vmware/PowerCLI-Example-Scripts/tree/master/Modules/VMware.Hv.Helper

Get-Module -ListAvailable *VM* | Import-Module
Import-Module VMware.hv.helper
$emailBody="Message to Users"
$emailSubject="Planned restart of all Virtual Desktops"
$emailSmtpServer="smtp.example.com"
$emailFrom="noreply@example.com"
$hvServer="connserver.example.com"
$hvUser="euc_automation_account"
$hvPassword="password"
$hvDomain="EXAMPLE"
$server=Connect-HVServer -Server $hvServer -User $hvUser -Password $hvPassword -Domain $hvDomain
$sessionSummaries=get-HVlocalsession

#Warn of Logoff in 3 days
foreach($sessionSummary in $sessionSummaries)
{
    $sessionLength=$(get-date) - $sessionSummary.SessionData.StartTime 
    if($sessionLength.Days -gt 4)
    {
        $desktopName=$sessionSummary.NamesData.DesktopName
        $sessionId=$sessionSummary.id
        $machineName=$sessionSummary.NamesData.MachineOrRDSServerDNS 
        $sessionUserName=$sessionSummary.NamesData.UserName -creplace '^[^\\]*\\', ''
        $sessionEmail=(((Get-ADUser $sessionUserName -Properties mail | select mail) -replace "@{mail=","") -replace "}","")
        $global:DefaultHVServers[0].ExtensionData.Session.Session_SendMessage($session.id,$emailSubject,$emailBody)
        Send-MailMessage -To $sessionEmail -From $emailFrom -SmtpServer $emailSmtpServer -Subject $emailSubject  -Body $emailBody
    }
}

#Wait 3 Days
Start-Sleep -Seconds 259200


#Logoff all desktops that have sessions longer then 5 days
foreach($sessionSummary in $sessionSummaries)
{
    $sessionLength=$(get-date) - $sessionSummary.SessionData.StartTime 
    if($sessionLength.Days -gt 5)
    {
        $sessionId=$sessionSummary.id
        $machineName=$sessionSummary.NamesData.MachineOrRDSServerDNS
         $global:DefaultHVServers[0].ExtensionData.Session.Session_LogoffForced($sessionId)
         $global:DefaultHVServers[0].ExtensionData.Session.Session_Restart($sessionId)
        
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *