Pawel Serwan Blog

Citrix, Microsoft and other stuff

[Powershell] Citrix XenApp Monitoring Script ver. 2.1

2 Comments

Monitoring

I got few questions regarding my Citrix XenApp monitoring script written in Powershell. I’ve decided to share with you it’s second better and improved version which has additional conditions on checking if really Citrix ICA connections was launched properly and your Citrix application is available for interaction with user. What is also improved is the overall time needed for the script to run. Right now all logons happen simultaneously thanks to which the script finishes below 2 minutes ( I tested that for about 20 servers). So you have now possibility to schedule a task that will be running more frequent and you will be able to better check health of your Citrix XenApp environment.

Before I share my script please check some prerequisites that are required by a script to execute properly:

1. You must have Citrix Receiver for Windows installed.
2. This script will only work in the x86 version of Powershell. You run it manually like this: %SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -file “path to the script”
3. You would schedule it like this:
Program/Script: %SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe
Arguments: -ExecutionPolicy Bypass -file “path to the script”
4. You have to create a service account to be used by the scheduled task
5. To allow task to interact with the desktop you have to configure task to run only when the user is logged in
6. You have to set autologon in your Windows desktop or server according to: https://support.microsoft.com/en-us/kb/310584
7. You have to download PSTerminalServices Powershell module from: http://blogs.microsoft.co.il/scriptfanatic/2010/02/22/psterminalservices-powershell-module-for-terminal-services/
8. After that you have to place it under %SystemRoot%\syswow64\WindowsPowerShell\v1.0\Modules
9. In order for the script to interact with the ICO, it requires the following to be set in the registry:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Citrix\ICA Client\CCM
AllowLiveMonitoring REG_DWORD 1
AllowSimulationAPI REG_DWORD 1

And of course I would like to underline that original script was written by Stan Czerno and is available under below link:

http://www.czerno.com/blog/post/2014/06/11/powershell-script-to-launch-a-published-application-from-one-or-more-xenapp-servers

Let me know if you would have any questions or comments.

!!! There is a problem with Powershell code in WordPress. Please check in Windows Powershell ISE editor if everything is OK!!!

# This script launches a specified Published Application for one or more XenApp Servers.
# You can use to this as a Test to make sure the server is actually launching Published Applications
# It will also log the time is takes to logon.
# It can be run by Scheduled Task to check availability of the Citrix XenApp servers.

# You must have Citrix Receiver for Windows installed.

# This script will only work in the x86 version of Powershell

# You run it manually like this: %SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -file "path to script"

# You would schedule it like this:
# Program/Script: %SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe
# Arguments: -ExecutionPolicy Bypass -file C:\XenAppMonitoringScript\Check-XAAppLaunchReport.ps1
# You have to create a service account to be used by the scheduled task
# To allow task to interact with the desktop you have to configure task to run only when the user is logged in
# You have to set autologon in your Windows desktop or server according to: https://support.microsoft.com/en-us/kb/310584

#You have to download PSTerminalServices Powershell module from: http://blogs.microsoft.co.il/scriptfanatic/2010/02/22/psterminalservices-powershell-module-for-terminal-services/
# After that you have to place it under %SystemRoot%\syswow64\WindowsPowerShell\v1.0\Modules

# In order for the script to interact with the ICO, it requires the following to be set in the registry:
# HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Citrix\ICA Client\CCM
# AllowLiveMonitoring REG_DWORD 1
# AllowSimulationAPI REG_DWORD 1

# Parts of the script comes from: http://www.czerno.com/blog/post/2014/06/11/powershell-script-to-launch-a-published-application-from-one-or-more-xenapp-servers

# Created by: Paweł Serwan
# Date: 25.03.2015
# Version: 2.1


## ============================================================ ##
##                      User Variables                          ##
## ============================================================ ##

#Import Citrix modules from Citrix SDK
#Add-PSSnapin Citrix*

# Publish Application Name to launch
$pubapp = "YOUR APP NAME"

# List of Servers to test, one or more can be listed
# If more than one, use this format: "Server1","Server2","Server3"
# If all servers in the farm should be tested: 
# $XAServers = Get-XAServer | Select ServerName
$XAServers = Import-Csv "PATH TO THE CSV FILE WITH LIST OF SERVERS"
#CSV file should look like:
#ServerName
#Server1
#Server2

# User name
$user = "USERNAME"

# User password
$passwd = "PASSWORD"

# Domain Name
$domain = "YOUR DOMAIN"

# E-mail settings 
# If $emailFrom, $emailTo or $smtpServer are blank, no email will be sent
# Define multiple email addresses like "email@domain.com,email2@domain.com"
$emailFrom     = "MAIL_FROM@MYDOMAIN.COM"
$emailTo       = "MAIL_TO@MYDOMAIN.COM"
# If not using a CC address, leave the value blank
#$emailCC       = "mailCC@mydomain.com" 
$smtpServer    = "SMTP.MYDOMAIN.COM"

# The variable below sets how often to send an email if no "new" alerts are detected.
# For example, Server 1 is having issues, an email is sent. If the test is scheduled to run again in 15 minutes
# you may want to set the lag time to something greater than 15 minutes so you are not constantly sent emails
# about the same issue.
# If an existing alert still exists, it will not be sent again until this lag time is reached.
# Be sure to align this with how often you schedule the task.
# The variable is set in seconds, 7200 seconds (2 hours) is the default.
#$EmailAlertsLagTime = "7200"

# This next variable defines if the script will type "EXIT + press ENTER". 
# This is optional, I left it becuase it was cool. If using a Command Prompt as a Test App, 
# you can let the script actually type EXIT then press ENTER. Pretty cool if watching it interactively.
# If you are not using a Command Prompt as a test you probably will want to mark this as $False and 
# set the $logoffmethod as $True.
# If you choose this option, keep the Published Application as Command Prompt, typing in Notepad or Word
# will hang the logoff asking you to save the file.
$typeexit = $False

# Just sends the Logoff command.
# If using the $typeexit method above, leave this $False
$logoffmethod = $False

## ============================================================ ##
##                    END User Variables                        ##
## ============================================================ ##


# ==================== #
# Setup Log Files      #
# ==================== #
# Reads the current directory path from the location of this file
function Get-ScriptDirectory
{
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value;
    if($Invocation.PSScriptRoot)
    {
        $Invocation.PSScriptRoot;
    }
    Elseif($Invocation.MyCommand.Path)
    {
        Split-Path $Invocation.MyCommand.Path
    }
    else
    {
        $Invocation.InvocationName.Substring(0,$Invocation.InvocationName.LastIndexOf("\"));
    }
}
$currentDir =  Get-ScriptDirectory
$logfile = Join-Path $currentDir ("LaunchPublishedApp.log")
$PreviuosLogFile = Join-Path $currentDir ("LaunchPublishedApp_previuosrun.log")
$AlertsEmailed = Join-Path $currentDir ("LaunchPublishedApp_AlertsEmailed.log")
$CurrentAlerts = Join-Path $currentDir ("LaunchPublishedApp_AlertsCurrent.log")
$AlertEmail = Join-Path $currentDir ("LaunchPublishedApp_AlertsEmailTimeStamp.log")
rm $logfile -force -EA SilentlyContinue

# ==================== #
# Email Style          #
# ==================== #
$ErrorStyle = "style=""background-color: #000000; color: #FF3300;"""

#===================================================================== #
# Sends the results into a logfile as well as in the powershell window #
#===================================================================== #
Function LogMe() 
{
    Param( [parameter(Mandatory = $true, ValueFromPipeline = $true)] $logEntry,
	   [switch]$displaygreen,
	   [switch]$error,
	   [switch]$warning,
	   [switch]$displaynormal,
       [switch]$displayscriptstart,
       [switch]$displayscriptend
	   )
    if($error) { Write-Host "$logEntry" -Foregroundcolor Red; $logEntry = "[ERROR] $logEntry" }
	elseif($warning) { Write-Host "$logEntry" -Foregroundcolor Yellow; $logEntry = "[WARNING] $logEntry"}
	elseif ($displaynormal) { Write-Host "$logEntry" -Foregroundcolor White; $logEntry = "[INFO] $logEntry" }
	elseif($displaygreen) { Write-Host "$logEntry" -Foregroundcolor Green; $logEntry = "[SUCCESS] $logEntry" }
    elseif($displayscriptstart) { Write-Host "$logEntry" -Foregroundcolor Green; $logEntry = "[SCRIPT_START] $logEntry" }
    elseif($displayscriptend) { Write-Host "$logEntry" -Foregroundcolor Green; $logEntry = "[SCRIPT_END] $logEntry" }
    else { Write-Host "$logEntry"; $logEntry = "$logEntry" }

	$logEntry | Out-File $logFile -Append
}

# ============================ #
# Get Client Version Function  #
# ============================ #
function Get-ICAClientVersion{ 
    $ErrorActionPreference = "SilentlyContinue" 
    $ica_client = New-Object -ComObject 'Citrix.ICAClient' 
    if($ica_client) { return $ica_client.ClientVersion } 
    else { return 0 } 
} 

# ====================== #
# Time Elapsed Function  #
# ====================== #
function GetElapsedTime([datetime]$starttime) 
{
    $runtime = $(get-date) - $starttime
    $retStr = [string]::format("{0} sec(s)", $runtime.TotalSeconds)
    $retStr
}

# ===================== #
# Create Registry Item  #
# ===================== #
function CreateRegEntry ($RegPath,$RegName,$PropType,$Val)
{
try {New-ItemProperty -Path $RegPath -Name $RegName -PropertyType $PropType -Value $Val -ErrorAction Stop}
catch {$Script:RegError += $_.Exception.Message
      $_.Exception.Message  | LogMe -error
      }
}

# ===================== #
# Modify Registry Item  #
# ===================== #
function ModifyRegEntry ($RegPath,$RegName,$Val)
{
try {Set-ItemProperty -Path $RegPath -Name $RegName -Value $Val -ErrorAction Stop}
catch {$Script:RegError += $_.Exception.Message
      $_.Exception.Message  | LogMe -error
      }
}

################################################################################
# ============================================================================ #
#                           Start of Script                                    #
# ============================================================================ #
################################################################################
# === Script Start Time
$startTime = Get-Date
cls
"Script Started at $startTime" | LogMe -displayscriptstart

# Making sure Registry Entries exist
# If not, try to create or modify
# If they cannot be created or modified, logging an error 
# and skipping ICA test
$Path = "HKLM:SOFTWARE\Wow6432Node\Citrix\ICA Client\CCM"
$AllowLiveMonitoringName = "AllowLiveMonitoring"
$AllowSimulationAPIName = "AllowSimulationAPI"
$PropertyType = "DWORD"
$Value =  "1"
$AllowLiveMonitoring = Get-ItemProperty -Path $Path -Name $AllowLiveMonitoringName -ErrorAction SilentlyContinue
$AllowSimulationAPI = Get-ItemProperty -Path $Path -Name $AllowSimulationAPIName  -ErrorAction SilentlyContinue
if (!$AllowLiveMonitoring) 
{
"AllowLiveMonitoring does not exist, creating it" | LogMe -warning 
CreateRegEntry $Path $AllowLiveMonitoringName $PropertyType $Value
}
elseif ($AllowLiveMonitoring.AllowLiveMonitoring -ne "1")
{
"AllowLiveMonitoring Value does not equal 1, setting to 1" | LogMe -warning 
ModifyRegEntry $Path $AllowLiveMonitoringName $Value
}
if (!$AllowSimulationAPI)
{ 
"AllowSimulationAPI does not exist, creating it" | LogMe -warning 
CreateRegEntry $Path $AllowSimulationAPIName $PropertyType $Value
}
elseif ($AllowSimulationAPI.AllowSimulationAPI -ne "1")
{
"AllowSimulationAPI value exists but does not equal 1, setting to 1" | LogMe -warning 
ModifyRegEntry $Path $AllowSimulationAPIName $Value
}
if ($RegError -ne $Null) 
{
" " | LogMe
"Errors were encountered when trying to add or modify registry entries required for this script to work" | LogMe -error
"You will either need to run this script once as an Adminitrator or create the following registry entries manually:" | LogMe -error
" " | LogMe
"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Citrix\ICA Client\CCM, AllowLiveMonitoring, DWORD, 1" | LogMe -displaynormal
"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Citrix\ICA Client\CCM, AllowSimulationAPI, DWORD, 1" | LogMe -displaynormal
$ICAErrors += @"
<p $ErrorStyle>Errors were encountered when trying to add or modify registry entries required for this script to work. 
You will either need to run this script once as an Adminitrator or create the following registry entries manually:<br>
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Citrix\ICA Client\CCM, AllowLiveMonitoring, DWORD, 1
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Citrix\ICA Client\CCM, AllowSimulationAPI, DWORD, 1 /p>
"@
}

if ($RegError -eq $Null) 
{
    # Getting Client Version
    $ClientVersion = Get-ICAClientVersion
    Add-Type -AssemblyName System.Windows.Forms

    # Loading the LIB File
    try {Add-Type -Path "C:\Program Files (x86)\Citrix\ICA Client\WfIcaLib.dll"}
    catch 
        {$AddTypeError = $_.Exception.Message
        $_.Exception.Message  | LogMe -error
        }
        If ($AddTypeError -eq $Null)
        {
            #define new array of objects to store ICO connection information
            $connections = @()
            #define new array of objects to store Process ID information of new ICA connections
            $pids = @()
                        
                        
			for($i=0;$i -lt $XAServers.count;$i++)
			{

				$XAserver = $XAServers[$i].ServerName
  
                # Buidling the ICO and starting the ICA Connection to each server
                $ICA = New-Object WFICALib.ICAClientClass
				"Testing Published Application, $pubapp, on Server $XAServer" 
				$ICA.Address = "$XAserver"
				$ICA.Username = "$user"
				$ICA.SetProp("Password","$passwd")
				$ICA.Domain = "$domain"
				$ICA.InitialProgram  = "$pubapp"
				$ICA.Launch = $true
				$ICA.OutputMode = [WFICALib.OutputMode]::OutputModeNormal
				$ICA.DesiredHRes = 200
				$ICA.DesiredVRes = 400
				$ICA.DesiredColor = [WFICALib.ICAColorDepth]::Color16bit
				$ICA.TWIMode = $true
				"Launching ICA Session using Citrix Client version $ClientVersion"
				$LaunchTime = Get-Date
				"Connect Started at $script:LaunchTime" 
				#Launch Citrix app
				$ICA.Connect()
                
                sleep 2

                $connections += $ICA
				#Get PID of launched WFICA32 process
                $sessionID= get-Process -name wfica32|sort starttime -Descending | select -first 1
                $pids += $sessionID
            }

            #wait for ICA connections to launch
            sleep 40

            for($j=0;$j -lt $connections.count;$j++)
            {
                if ($connections[$j].IsConnected() -eq $true -and $connections[$j].Address -eq $XAServers[$j].ServerName)
                {
                    if ($pids[$j].MainWindowTitle -eq "TITLE OF THE WINDOW OF YOUR TESTED APPLICATION")    
                    {
                        "Test ICA Session found running on $($XAServers[$j].ServerName); logging off" | LogMe -displaygreen
                        
					    $logonelapsed = GetElapsedTime $LaunchTime
					    "Time taken to logon is: $logonelapsed" | LogMe -displaygreen
                        $connections[$j].Logoff() 
                    }
                    elseif ($pids[$j].MainWindowTitle -eq "Windows Logon" -or $pids[$j].MainWindowTitle -eq "Notepad" )
                    {
                        "Connection failed to server " + $($XAServers[$j].ServerName) | LogMe -Error
					    $ICAErrors += "<p $ErrorStyle>Error Connection to server <strong>$($XAServers[$j].ServerName).</strong></p>"                        
                        $ICAErrors += "<p $ErrorStyle>Please check for a hanged service (e.g. CpSvc) on server <strong>$($XAServers[$j].ServerName).</strong></p>"
                        $connections[$j].Logoff() 
                    }
                    else
                    {
                        "Connection failed to server " + $($XAServers[$j].ServerName) | LogMe -Error
					    $ICAErrors += "<p $ErrorStyle>Error Connection to server <strong>$($XAServers[$j].ServerName).</strong></p>"                        
                        $ICAErrors += "<p $ErrorStyle>Problem with logon process to server <strong>$($XAServers[$j].ServerName) - please check.</strong></p>"
                        $connections[$j].Logoff()                         
                    }
                }
                elseif ($connections[$j].IsConnected() -eq $false -and $connections[$j].Address -eq $XAServers[$j].ServerName)
                {
                    "Connection failed to server " + $($XAServers[$j].ServerName) | LogMe -Error
					$ICAErrors += "<p $ErrorStyle>Error Connection to server <strong>$($XAServers[$j].ServerName)</strong></p>"
					"Clicking OK in the Citrix Receiver dialog window" | LogMe -displaynormal    
               
					Add-Type @"
					using System;
					using System.Runtime.InteropServices;
					public class SFW {
					[DllImport("user32.dll")]
					[return: MarshalAs(UnmanagedType.Bool)]
					public static extern bool SetForegroundWindow(IntPtr hWnd);
					}
"@

					"Finding a window named Citrix Receiver" | LogMe -displaynormal
					$hwnd = (get-process Receiver).MainWindowHandle # just one Receiver window must be opened!
					if ($hwnd -ne 0)
					{
						"Set Foreground Window to Citrix Receiver" | LogMe -displaynormal
						[SFW]::SetForegroundWindow($hwnd)
						"Sending the Enter command to Window" | LogMe -displaynormal
						[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
					}
					else 
					{
						"There was no Window titled Citrix Receiver, the error is most likely due to the script" | LogMe -warning
					}
            
                }
                else
                {
                	$ICAErrors += "<p $ErrorStyle>Error launching application <strong>$pubapp</strong> on server <strong>$XAServer</strong></p>"
					"Did not detect a Successful Logon or a Connect Failure to server $XAServers[$j].ServerName" | LogMe -Error
					"Assuming Logon Failure, Server is not available or the Application is not available" | LogMe -Error
					"Check the Published Application, Server Logons are Enabled, User Account and/or Script User Variables" | LogMe -Error  
                
                }             


            }

        }
        else 
		{
			$ICAErrors += @"
            <p $ErrorStyle>Errors were encountered when trying to load WfIcaLib.dll.<br>
            $AddTypeError</p>
"@
		}
}

# Get the Current Time for Email Alert Time Stamp
$CurrTime = Get-Date -format g

# Checking to see if there were any Errors Detected
# If there were, update the CurrentAlerts Log File for later comparison
if ($ICAErrors -ne $Null) 
    {
    if (Test-Path $CurrentAlerts) { clear-content $CurrentAlerts }
    foreach ($line in $ICAErrors) {$Line | Add-Content $CurrentAlerts}
            
        # Get Content from Alert Log File, we want the first line, which should be the previuos time stamp.
        if (Test-Path $AlertEmail) 
            { $AlertFileTime = gc $AlertEmail -TotalCount 1 } 

        # Check to see if the Time Span for sending alerts has passed
        if ($AlertFileTime)
            {$AlertTimeSpan = New-TimeSpan $AlertFileTime $(Get-Date -format g)
            $AlertTimeDifference = $AlertTimeSpan.TotalSeconds 
                if (!$AlertTimeDifference) { $SendEmail = $True }
                if ($AlertTimeDifference -ge $EmailAlertsLagTime) { $SendEmail = $True }
                else { $SendEmail = $False }
            }
        if (!$AlertFileTime) { $SendEmail = $True }

        # Checking Alert Log Contents from last run for comparison
        if (Test-Path $AlertsEmailed) { $AlertLogContents = gc $AlertsEmailed }

        # Checking Current Errors and Warnings found this duration for comparison
        if (Test-Path $CurrentAlerts) { $CurrentAlertsContents = gc $CurrentAlerts }

        # If the Alerts Email Log is empty but the Current Log is not, there are new alerts.
        If (!$AlertLogContents -and $CurrentAlertsContents) 
            {
            $NewAlerts = $True
            $SendEmail = $True 
            " " | LogMe
            "New Alerts Detected"  | LogMe -warning
            } 
        # If the Alert Email Log and the Current Alert Log matches then there are most likely no new errors
        If ($AlertLogContents -and $CurrentAlertsContents) 
            {
            $AlertsDiff = compare-object $CurrentAlertsContents $AlertLogContents | Measure
            If ($AlertsDiff.count -ne 0) 
                    { $NewAlerts = $True 
                    " " | LogMe
                    "New Alerts Detected"  | LogMe -warning
                    }
                else 
                    { $NewAlerts = $False 
                    " " | LogMe
                    "No New Alerts Detected"  | LogMe -displaynormal
                    } 
            }

    }
else {if (Test-Path $CurrentAlerts) 
    {clear-content $CurrentAlerts}

}

#=============================================================================================
#                                 Email Section
#=============================================================================================  
If (($NewAlerts -eq $True) -or ($SendEmail -eq $True)) 
    { 
        if (Test-Path $AlertsEmailed) { clear-content $AlertsEmailed }
        foreach ($line in $ICAErrors) { $Line | Add-Content $AlertsEmailed }

        # Setting MailFlag for the validation and error handling
        $MailFlag = $false 

        If(!$emailFrom) { $MailFlag = $True; Write-Warning "From Email is NULL" | LogMe -error }
        If(!$emailTo) { $MailFlag = $True; Write-Warning "To Email is NULL" | LogMe -error }
        If(!$smtpServer) { $MailFlag = $True; Write-Warning "SMTP Server is NULL" | LogMe -error }

        # $MailFlag = $True

        # Send email only if From, To and SMTP adress are not null
        if($MailFlag -match $True) { "Email could not send as the email parameters (FROM/TO/SMTP) failed"  | LogMe -error}
        
        # Send email only if there is either an Error or Warning Detected
        $BODY = $ICAErrors
        $msg = new-object System.Net.Mail.MailMessage
        $msg.From=$emailFrom
        $msg.to.Add($emailTo)
        if($emailCC) { $msg.cc.add($emailCC) }
        $msg.Subject=$emailSubject
        $msg.IsBodyHtml=$true
        $msg.Body=$BODY
        #$msg.Attachments.Add($logfile)
        $smtp = new-object System.Net.Mail.SmtpClient
        $smtp.host=$smtpServer
        Try { $smtp.Send($msg)
            " " | LogMe
            "Email Sent" | LogMe -displaygreen }
        Catch { 
            "" | LogMe
            "Error Sending Email. See Error Messages Below:" | LogMe -error 
            "Error Message: " + $_.Exception.Message | LogMe -error
            "Error Item: " + $_.Exception.ItemName | LogMe -error
                  }
        Start-Sleep 2
        $msg.Dispose()
        if (Test-Path $AlertEmail) { clear-content $AlertEmail }
        $CurrTime | Add-Content $AlertEmail
        }
else 
    { 
    " " | LogMe
    "Not sending an email since there were no new Errors detected" | LogMe -displaynormal
    }



$scriptelapsed = GetElapsedTime $startTime
" " | LogMe
"Total Elapsed Script Time: $scriptelapsed" | LogMe -displaygreen
" " | LogMe
"Script Ended at $(get-date)" | LogMe -displayscriptend
" " | LogMe

# Killing left over processes from Receiver so the script will work the next time it is executed
# This is really only needed when running as a scheduled task
# If these processes are allowed to remain the Connection fails after the second try
$KillApps = $True
if ($KillApps -eq $True){

try {kill -name wfcrun32 -Force -ErrorAction SilentlyContinue}
catch {$_.Exception.Message | LogMe -warning}

try {kill -name concentr -Force -ErrorAction SilentlyContinue}
catch {$_.Exception.Message | LogMe -warning}

try {kill -name redirector -Force -ErrorAction SilentlyContinue}
catch {$_.Exception.Message | LogMe -warning}

try {kill -name wfica32 -Force -ErrorAction SilentlyContinue}
catch {$_.Exception.Message | LogMe -warning}

try {kill -name receiver -Force -ErrorAction SilentlyContinue}
catch {$_.Exception.Message | LogMe -warning}

try {kill -name ssonsvr -Force -ErrorAction SilentlyContinue}
catch {$_.Exception.Message | LogMe -warning}
}

# Creating Log file for previuos ran jobs
# File is cleared when it reaches 1MB
$size = Get-ChildItem $PreviuosLogFile
if ($size.length -ge 1048576)
    {clear-content $PreviuosLogFile}
$LogPattern = @("[SUCCESS]","[ERROR]","[WARNING]","[SCRIPT_START]","[SCRIPT_END]")
if (Test-Path $LogFile) {Get-Content $LogFile | Select-String -Pattern $LogPattern -SimpleMatch | add-Content $PreviuosLogFile}

EXIT

#==============================================================================================
# END OF SCRIPT
#==============================================================================================


Advertisements

2 thoughts on “[Powershell] Citrix XenApp Monitoring Script ver. 2.1

  1. Hi Paul
    Thanks for taking your valuable time to share your time and script. Really appreciate it. I would be interested to see how the output looks like . Could you post that as well please if you get some time. Thanks again . Suresh

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s