-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathXA-and-XD-HealthCheck.ps1
1945 lines (1588 loc) · 78.8 KB
/
XA-and-XD-HealthCheck.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#==============================================================================================
# Created on: 11.2014 modfied 10.2018 Version: 1.4.6
# Created by: Sacha / sachathomet.ch & Contributers (see changelog at EOF)
# File name: XA-and-XD-HealthCheck.ps1
#
# Description: This script checks a Citrix XenDesktop and/or XenApp 7.x Farm
# It generates a HTML output File which will be sent as Email.
#
# Initial versions tested on XenApp/XenDesktop 7.6 and XenDesktop 5.6
# Newest version tested on XenApp/XenDesktop 7.11-7.13
#
# Prerequisite: Config file, a XenDesktop Controller with according privileges necessary
# Config file: In order for the script to work properly, it needs a configuration file.
# This has the same name as the script, with extension _Parameters.
# The script name can't contain any another point, even with a version.
# Example: Script = "XA and XD HealthCheck.ps1", Config = "XA and XD HealthCheck_Parameters.xml"
#
# Call by : Manual or by Scheduled Task, e.g. once a day
# !! If you run it as scheduled task you need to add with argument "non interactive"
# or your user has interactive persmission!
#
#
#==============================================================================================
# Don't change below here if you don't know what you are doing ...
#==============================================================================================
#==============================================================================================
#Define variable to count script execution time and clear screen
$scriptstart = Get-Date
Clear-Host
#==============================================================================================
# Load only the snap-ins, which are used
if ($null -eq (Get-PSSnapin "Citrix.*" -EA silentlycontinue)) {
try { Add-PSSnapin Citrix.* -ErrorAction Stop }
catch { write-error "Error Get-PSSnapin Citrix.Broker.Admin.* Powershell snapin"; Return }
}
#==============================================================================================
# Import Variables from XML:
If (![string]::IsNullOrEmpty($hostinvocation)) {
[string]$Global:ScriptPath = [System.IO.Path]::GetDirectoryName([System.Windows.Forms.Application]::ExecutablePath)
[string]$Global:ScriptFile = [System.IO.Path]::GetFileName([System.Windows.Forms.Application]::ExecutablePath)
[string]$global:ScriptName = [System.IO.Path]::GetFileNameWithoutExtension([System.Windows.Forms.Application]::ExecutablePath)
} ElseIf ($Host.Version.Major -lt 3) {
[string]$Global:ScriptPath = Split-Path -parent $MyInvocation.MyCommand.Definition
[string]$Global:ScriptFile = Split-Path -Leaf $script:MyInvocation.MyCommand.Path
[string]$global:ScriptName = $ScriptFile.Split('.')[0].Trim()
} Else {
[string]$Global:ScriptPath = $PSScriptRoot
[string]$Global:ScriptFile = Split-Path -Leaf $PSCommandPath
[string]$global:ScriptName = $ScriptFile.Split('.')[0].Trim()
}
Set-StrictMode -Version Latest
# Import parameter file
$Global:ParameterFile = $ScriptName + "_Parameters.xml"
$Global:ParameterFilePath = $ScriptPath
[xml]$cfg = Get-Content ($ParameterFilePath + "\" + $ParameterFile) # Read content of XML file
# Import variables
Function New-XMLVariables {
# Create a variable reference to the XML file
$cfg.Settings.Variables.Variable | ForEach-Object {
# Set Variables contained in XML file
$VarValue = $_.Value
$CreateVariable = $True # Default value to create XML content as Variable
switch ($_.Type) {
# Format data types for each variable
'[string]' { $VarValue = [string]$VarValue } # Fixed-length string of Unicode characters
'[char]' { $VarValue = [char]$VarValue } # A Unicode 16-bit character
'[byte]' { $VarValue = [byte]$VarValue } # An 8-bit unsigned character
'[bool]' { If ($VarValue.ToLower() -eq 'false'){$VarValue = [bool]$False} ElseIf ($VarValue.ToLower() -eq 'true'){$VarValue = [bool]$True} } # An boolean True/False value
'[int]' { $VarValue = [int]$VarValue } # 32-bit signed integer
'[long]' { $VarValue = [long]$VarValue } # 64-bit signed integer
'[decimal]' { $VarValue = [decimal]$VarValue } # A 128-bit decimal value
'[single]' { $VarValue = [single]$VarValue } # Single-precision 32-bit floating point number
'[double]' { $VarValue = [double]$VarValue } # Double-precision 64-bit floating point number
'[DateTime]' { $VarValue = [DateTime]$VarValue } # Date and Time
'[Array]' { $VarValue = [Array]$VarValue.Split(',') } # Array
'[Command]' { $VarValue = Invoke-Expression $VarValue; $CreateVariable = $False } # Command
}
If ($CreateVariable) { New-Variable -Name $_.Name -Value $VarValue -Scope $_.Scope -Force }
}
}
New-XMLVariables
$PvsWriteMaxSizeInGB = $PvsWriteMaxSize * 1Gb
ForEach ($DeliveryController in $DeliveryControllers){
If ($DeliveryController -ieq "LocalHost"){
$DeliveryController = [System.Net.DNS]::GetHostByName('').HostName
}
If (Test-Connection $DeliveryController) {
$AdminAddress = $DeliveryController
break
}
}
$ReportDate = (Get-Date -UFormat "%A, %d. %B %Y %R")
$currentDir = Split-Path $MyInvocation.MyCommand.Path
$outputpath = Join-Path $currentDir "" #add here a custom output folder if you wont have it on the same directory
$logfile = Join-Path $outputpath ("CTXXDHealthCheck.log")
$resultsHTM = Join-Path $outputpath ("CTXXDHealthCheck.htm") #add $outputdate in filename if you like
#Header for Table "XD/XA Controllers" Get-BrokerController
$XDControllerFirstheaderName = "ControllerServer"
$XDControllerHeaderNames = "Ping", "State","DesktopsRegistered", "ActiveSiteServices"
$XDControllerHeaderWidths = "2", "2", "2", "10"
$XDControllerTableWidth= 1200
foreach ($disk in $diskLettersControllers)
{
$XDControllerHeaderNames += "$($disk)Freespace"
$XDControllerHeaderWidths += "4"
}
$XDControllerHeaderNames += "AvgCPU", "MemUsg", "Uptime"
$XDControllerHeaderWidths += "4", "4", "4"
#Header for Table "Fail Rates" FUTURE
#$CTXFailureFirstheaderName = "Checks"
#$CTXFailureHeaderNames = "#","in Percentage", "CauseServiceInterruption","CausePartialServiceInterruption"
#$CTXFailureHeaderWidths = "2", "2", "2", "2"
#$CTXFailureTableWidth= 900
#Header for Table "CTX Licenses" Get-BrokerController
$CTXLicFirstheaderName = "LicenseName"
$CTXLicHeaderNames = "LicenseServer", "Count","InUse", "Available"
$CTXLicHeaderWidths = "4", "2", "2", "2"
$CTXLicTableWidth= 900
#Header for Table "MachineCatalogs" Get-BrokerCatalog
$CatalogHeaderName = "CatalogName"
$CatalogHeaderNames = "AssignedToUser", "AssignedToDG", "NotToUserAssigned","ProvisioningType", "AllocationType", "MinimumFunctionalLevel", "UsedMCSSnapshot"
$CatalogWidths = "4", "8", "8", "8", "8", "4", "4"
$CatalogTablewidth = 900
#Header for Table "DeliveryGroups" Get-BrokerDesktopGroup
$AssigmentFirstheaderName = "DeliveryGroup"
$vAssigmentHeaderNames = "PublishedName","DesktopKind", "SessionSupport", "ShutdownAfterUse", "TotalMachines","DesktopsAvailable","DesktopsUnregistered", "DesktopsInUse","DesktopsFree", "MaintenanceMode", "MinimumFunctionalLevel"
$vAssigmentHeaderWidths = "4", "4", "4", "4", "4", "4", "4", "4", "2", "2", "2"
$Assigmenttablewidth = 900
#Header for Table "VDI Checks" Get-BrokerMachine
$VDIfirstheaderName = "virtualDesktops"
$VDIHeaderNames = "CatalogName","DeliveryGroup","PowerState", "Ping", "MaintMode", "Uptime","LastConnect", "RegState","VDAVersion","AssociatedUserNames", "WriteCacheType", "WriteCacheSize", "Tags", "HostedOn", "displaymode", "EDT_MTU", "OSBuild", "MCSVDIImageOutOfDate"
$VDIHeaderWidths = "4", "4", "4","4", "4", "4", "4","4", "4", "4", "4", "4", "4", "4", "4", "4", "4", "4"
$VDItablewidth = 1200
#Header for Table "XenApp Checks" Get-BrokerMachine
$XenAppfirstheaderName = "virtualApp-Servers"
$XenAppHeaderNames = "CatalogName", "DeliveryGroup", "Serverload", "Ping", "MaintMode","Uptime", "RegState", "VDAVersion", "Spooler", "CitrixPrint", "OSBuild", "MCSImageOutOfDate"
$XenAppHeaderWidths = "4", "4", "4", "4", "4", "4", "4", "4", "4", "4", "4", "4"
foreach ($disk in $diskLettersWorkers)
{
$XenAppHeaderNames += "$($disk)Freespace"
$XenAppHeaderWidths += "4"
}
if ($ShowConnectedXenAppUsers -eq "1") {
$XenAppHeaderNames += "AvgCPU", "MemUsg", "ActiveSessions", "WriteCacheType", "WriteCacheSize", "ConnectedUsers" , "Tags","HostedOn"
$XenAppHeaderWidths +="4", "4", "4", "4", "4", "4", "4","4"
}
else {
$XenAppHeaderNames += "AvgCPU", "MemUsg", "ActiveSessions", "WriteCacheType", "WriteCacheSize", "Tags","HostedOn"
$XenAppHeaderWidths +="4", "4", "4", "4", "4", "4","4"
}
$XenApptablewidth = 1200
#==============================================================================================
#log function
function LogMe() {
Param(
[parameter(Mandatory = $true, ValueFromPipeline = $true)] $logEntry,
[switch]$display,
[switch]$error,
[switch]$warning,
[switch]$progress
)
if ($error) { $logEntry = "[ERROR] $logEntry" ; Write-Host "$logEntry" -Foregroundcolor Red }
elseif ($warning) { Write-Warning "$logEntry" ; $logEntry = "[WARNING] $logEntry" }
elseif ($progress) { Write-Host "$logEntry" -Foregroundcolor Green }
elseif ($display) { Write-Host "$logEntry" }
#$logEntry = ((Get-Date -uformat "%D %T") + " - " + $logEntry)
$logEntry | Out-File $logFile -Append
}
#==============================================================================================
function Ping([string]$hostname, [int]$timeout = 200) {
$ping = new-object System.Net.NetworkInformation.Ping #creates a ping object
try { $result = $ping.send($hostname, $timeout).Status.ToString() }
catch { $result = "Failure" }
return $result
}
#==============================================================================================
# The function will check the processor counter and check for the CPU usage. Takes an average CPU usage for 5 seconds. It check the current CPU usage for 5 secs.
Function CheckCpuUsage()
{
param ($hostname)
Try { $CpuUsage=(Get-WmiObject -computer $hostname -class win32_processor | Measure-Object -property LoadPercentage -Average | Select-Object -ExpandProperty Average)
$CpuUsage = [math]::round($CpuUsage, 1); return $CpuUsage
} Catch { "Error returned while checking the CPU usage. Perfmon Counters may be fault" | LogMe -error; return 101 }
}
#==============================================================================================
# The function check the memory usage and report the usage value in percentage
Function CheckMemoryUsage()
{
param ($hostname)
Try
{ $SystemInfo = (Get-WmiObject -computername $hostname -Class Win32_OperatingSystem -ErrorAction Stop | Select-Object TotalVisibleMemorySize, FreePhysicalMemory)
$TotalRAM = $SystemInfo.TotalVisibleMemorySize/1MB
$FreeRAM = $SystemInfo.FreePhysicalMemory/1MB
$UsedRAM = $TotalRAM - $FreeRAM
$RAMPercentUsed = ($UsedRAM / $TotalRAM) * 100
$RAMPercentUsed = [math]::round($RAMPercentUsed, 2);
return $RAMPercentUsed
} Catch { "Error returned while checking the Memory usage. Perfmon Counters may be fault" | LogMe -error; return 101 }
}
#==============================================================================================
# The function check the HardDrive usage and report the usage value in percentage and free space
Function CheckHardDiskUsage()
{
param ($hostname, $deviceID)
Try
{
$HardDisk = $null
$HardDisk = Get-WmiObject Win32_LogicalDisk -ComputerName $hostname -Filter "DeviceID='$deviceID'" -ErrorAction Stop | Select-Object Size,FreeSpace
if ($null -ne $HardDisk)
{
$DiskTotalSize = $HardDisk.Size
$DiskFreeSpace = $HardDisk.FreeSpace
$frSpace=[Math]::Round(($DiskFreeSpace/1073741824),2)
$PercentageDS = (($DiskFreeSpace / $DiskTotalSize ) * 100); $PercentageDS = [math]::round($PercentageDS, 2)
Add-Member -InputObject $HardDisk -MemberType NoteProperty -Name PercentageDS -Value $PercentageDS
Add-Member -InputObject $HardDisk -MemberType NoteProperty -Name frSpace -Value $frSpace
}
return $HardDisk
} Catch { "Error returned while checking the Hard Disk usage. Perfmon Counters may be fault" | LogMe -error; return $null }
}
#==============================================================================================
Function writeHtmlHeader
{
param($title, $fileName)
$date = $ReportDate
$head = @"
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>
<title>$title</title>
<STYLE TYPE="text/css">
<!--
td {
font-family: Tahoma;
font-size: 11px;
border-top: 1px solid #999999;
border-right: 1px solid #999999;
border-bottom: 1px solid #999999;
border-left: 1px solid #999999;
padding-top: 0px;
padding-right: 0px;
padding-bottom: 0px;
padding-left: 0px;
overflow: hidden;
}
body {
margin-left: 5px;
margin-top: 5px;
margin-right: 0px;
margin-bottom: 10px;
table {
table-layout:fixed;
border: thin solid #000000;
}
-->
</style>
</head>
<body>
<table width='1200'>
<tr bgcolor='#CCCCCC'>
<td colspan='7' height='48' align='center' valign="middle">
<font face='tahoma' color='#003399' size='4'>
<strong>$title - $date</strong></font>
</td>
</tr>
</table>
"@
$head | Out-File $fileName
}
# ==============================================================================================
Function writeTableHeader
{
param($fileName, $firstheaderName, $headerNames, $headerWidths, $tablewidth)
$tableHeader = @"
<table width='$tablewidth'><tbody>
<tr bgcolor=#CCCCCC>
<td width='6%' align='center'><strong>$firstheaderName</strong></td>
"@
$i = 0
while ($i -lt $headerNames.count) {
$headerName = $headerNames[$i]
$headerWidth = $headerWidths[$i]
$tableHeader += "<td width='" + $headerWidth + "%' align='center'><strong>$headerName</strong></td>"
$i++
}
$tableHeader += "</tr>"
$tableHeader | Out-File $fileName -append
}
# ==============================================================================================
Function writeTableFooter
{
param($fileName)
"</table><br/>"| Out-File $fileName -append
}
#==============================================================================================
Function writeData
{
param($data, $fileName, $headerNames)
$tableEntry =""
$data.Keys | Sort-Object | ForEach-Object {
$tableEntry += "<tr>"
$computerName = $_
$tableEntry += ("<td bgcolor='#CCCCCC' align=center><font color='#003399'>$computerName</font></td>")
#$data.$_.Keys | foreach {
$headerNames | ForEach-Object {
#"$computerName : $_" | LogMe -display
try {
if ($data.$computerName.$_[0] -eq "SUCCESS") { $bgcolor = "#387C44"; $fontColor = "#FFFFFF" }
elseif ($data.$computerName.$_[0] -eq "WARNING") { $bgcolor = "#FF7700"; $fontColor = "#FFFFFF" }
elseif ($data.$computerName.$_[0] -eq "ERROR") { $bgcolor = "#FF0000"; $fontColor = "#FFFFFF" }
else { $bgcolor = "#CCCCCC"; $fontColor = "#003399" }
$testResult = $data.$computerName.$_[1]
}
catch {
$bgcolor = "#CCCCCC"; $fontColor = "#003399"
$testResult = ""
}
$tableEntry += ("<td bgcolor='" + $bgcolor + "' align=center><font color='" + $fontColor + "'>$testResult</font></td>")
}
$tableEntry += "</tr>"
}
$tableEntry | Out-File $fileName -append
}
# ==============================================================================================
Function writeHtmlFooter
{
param($fileName)
@"
</table>
<table width='1200'>
<tr bgcolor='#CCCCCC'>
<td colspan='7' height='25' align='left'>
<font face='courier' color='#000000' size='2'>
<strong>Uptime Threshold: </strong> $maxUpTimeDays days <br>
<strong>Database: </strong> $dbinfo <br>
<strong>LicenseServerName: </strong> $lsname <strong>LicenseServerPort: </strong> $lsport <br>
<strong>ConnectionLeasingEnabled: </strong> $CLeasing <br>
<strong>LocalHostCacheEnabled: </strong> $LHC <br>
<strong>HypervisorConnectionstate: </strong> $HVCS <br>
</font>
</td>
</table>
</body>
</html>
"@ | Out-File $FileName -append
}
# ==============================================================================================
Function ToHumanReadable()
{
param($timespan)
If ($timespan.TotalHours -lt 1) {
return $timespan.Minutes + "minutes"
}
$sb = New-Object System.Text.StringBuilder
If ($timespan.Days -gt 0) {
[void]$sb.Append($timespan.Days)
[void]$sb.Append(" days")
[void]$sb.Append(", ")
}
If ($timespan.Hours -gt 0) {
[void]$sb.Append($timespan.Hours)
[void]$sb.Append(" hours")
}
If ($timespan.Minutes -gt 0) {
[void]$sb.Append(" and ")
[void]$sb.Append($timespan.Minutes)
[void]$sb.Append(" minutes")
}
return $sb.ToString()
}
# if enabled for Citrix Cloud set the credential profile:
# Help from https://www.citrix.com/blogs/2016/07/01/introducing-remote-powershell-sdk-v2-for-citrix-cloud/ and
# from https://hallspalmer.wordpress.com/2019/02/19/manage-citrix-cloud-using-powershell/
if ( $CitrixCloudCheck -eq "1" ) {
Set-XDCredentials -CustomerId $CustomerID -SecureClientFile $SecureClientFile -ProfileType CloudApi -StoreAs default
}
# ==============================================================================================
<#
.SYNOPSIS
Get information about user that set maintenance mode.
.DESCRIPTION
Over the Citrix XenDeesktop or XenApp log database, you can finde the user that
set the maintenance mode of an worker.
This is version 1.0.
.PARAMETER AdminAddress
Specifies the address of the Delivery Controller to which the PowerShell module will connect. This can be provided as a host name or an IP address.
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
.EXAMPLE
Get-CitrixMaintenanceInfo
Get the informations on an delivery controller with nedded credentials.
.EXAMPLE
Get-CitrixMaintenanceInfo -AdminAddress server.domain.tld -Credential (Get-Credential)
Use sever.domain.tld to get the log informations and use credentials.
.LINK
http://www.beckmann.ch/blog/2016/11/01/get-user-who-set-maintenance-mode-for-a-server-or-client/
#>
function Get-CitrixMaintenanceInfo {
[CmdletBinding()]
[OutputType([System.Management.Automation.PSCustomObject])]
param
(
[Parameter(Mandatory = $false,
ValueFromPipeline = $true,
Position = 0)]
[System.String[]]$AdminAddress = 'localhost',
[Parameter(Mandatory = $false,
ValueFromPipeline = $true,
Position = 1)]
[System.Management.Automation.PSCredential]$Credential
) # Param
Try {
$PSSessionParam = @{ }
If ($null -ne $Credential) { $PSSessionParam['Credential'] = $Credential } #Splatting
If ($null -ne $AdminAddress) { $PSSessionParam['ComputerName'] = $AdminAddress } #Splatting
# Create Session
$Session = New-PSSession -ErrorAction Stop @PSSessionParam
# Create script block for invoke command
$ScriptBlock = {
if ($null -eq (Get-PSSnapin "Get-PSSnapin Citrix.ConfigurationLogging.Admin.*" -ErrorAction silentlycontinue)) {
try { Add-PSSnapin Citrix.ConfigurationLogging.Admin.* -ErrorAction Stop } catch { write-error "Error Get-PSSnapin Citrix.ConfigurationLogging.Admin.* Powershell snapin"; Return }
} #If
$Date = Get-Date
$StartDate = $Date.AddDays(-7) # Hard coded value for how many days back
$EndDate = $Date
# Command to get the informations from log
$LogEntrys = Get-LogLowLevelOperation -MaxRecordCount 1000000 -Filter { StartTime -ge $StartDate -and EndTime -le $EndDate } | Where-Object { $_.Details.PropertyName -eq 'MAINTENANCEMODE' } | Sort-Object EndTime -Descending
# Build an object with the data for the output
[array]$arrMaintenance = @()
ForEach ($LogEntry in $LogEntrys) {
$TempObj = New-Object -TypeName psobject -Property @{
User = $LogEntry.User
TargetName = $LogEntry.Details.TargetName
NewValue = $LogEntry.Details.NewValue
PreviousValue = $LogEntry.Details.PreviousValue
StartTime = $LogEntry.Details.StartTime
EndTime = $LogEntry.Details.EndTime
} #TempObj
$arrMaintenance += $TempObj
} #ForEach
$arrMaintenance
} # ScriptBlock
# Run the script block with invoke-command, return the values and close the session
$MaintLogs = Invoke-Command -Session $Session -ScriptBlock $ScriptBlock -ErrorAction Stop
Write-Output $MaintLogs
Remove-PSSession -Session $Session -ErrorAction SilentlyContinue
} Catch {
Write-Warning "Error occurs: $_"
} # Try/Catch
} # Get-CitrixMaintenanceInfo
#==============================================================================================
$wmiOSBlock = {param($computer)
try { $wmi=Get-WmiObject -Class Win32_OperatingSystem -ComputerName $computer -ErrorAction Stop }
catch { $wmi = $null }
return $wmi
}
#==============================================================================================
# == MAIN SCRIPT ==
#==============================================================================================
Remove-Item $logfile -force -EA SilentlyContinue
Remove-Item $resultsHTM -force -EA SilentlyContinue
"#### Begin with Citrix XenDestop / XenApp HealthCheck ######################################################################" | LogMe -display -progress
" " | LogMe -display -progress
# get some farm infos, which will be presented in footer
$dbinfo = Get-BrokerDBConnection -AdminAddress $AdminAddress
$brokersiteinfos = Get-BrokerSite
$lsname = $brokersiteinfos.LicenseServerName
$lsport = $brokersiteinfos.LicenseServerPort
$CLeasing = $brokersiteinfos.ConnectionLeasingEnabled
$LHC =$brokersiteinfos.LocalHostCacheEnabled
$BrkrHvsCon = Get-Brokerhypervisorconnection
$HVCS =$BrkrHvsCon.State
# Log the loaded Citrix PS Snapins
(Get-PSSnapin "Citrix.*" -EA silentlycontinue).Name | ForEach-Object {"PSSnapIn: " + $_ | LogMe -display -progress}
#== Controller Check ============================================================================================
"Check Controllers #############################################################################" | LogMe -display -progress
" " | LogMe -display -progress
$ControllerResults = @{}
$Controllers = Get-BrokerController -AdminAddress $AdminAddress
# Get first DDC version (should be all the same unless an upgrade is in progress)
$ControllerVersion = $Controllers[0].ControllerVersion
"Version: $controllerversion " | LogMe -display -progress
if ($ControllerVersion -lt 7 ) {
"XenDesktop/XenApp Version below 7.x ($controllerversion) - only DesktopCheck will be performed" | LogMe -display -progress
#$ShowXenAppTable = 0 #doesent work with XML variables
Set-Variable -Name ShowXenAppTable -Value 0
} else {
"XenDesktop/XenApp Version above 7.x ($controllerversion) - XenApp and DesktopCheck will be performed" | LogMe -display -progress
}
foreach ($Controller in $Controllers) {
$tests = @{}
#Name of $Controller
$ControllerDNS = $Controller | ForEach-Object{ $_.DNSName }
"Controller: $ControllerDNS" | LogMe -display -progress
#Ping $Controller
$result = Ping $ControllerDNS 100
if ($result -ne "SUCCESS") { $tests.Ping = "Error", $result }
else { $tests.Ping = "SUCCESS", $result
#Now when Ping is ok also check this:
#State of this controller
$ControllerState = $Controller | ForEach-Object{ $_.State }
"State: $ControllerState" | LogMe -display -progress
if ($ControllerState -ne "Active") { $tests.State = "ERROR", $ControllerState }
else { $tests.State = "SUCCESS", $ControllerState }
#DesktopsRegistered on this controller
$ControllerDesktopsRegistered = $Controller | ForEach-Object{ $_.DesktopsRegistered }
"Registered: $ControllerDesktopsRegistered" | LogMe -display -progress
$tests.DesktopsRegistered = "NEUTRAL", $ControllerDesktopsRegistered
#ActiveSiteServices on this controller
$ActiveSiteServices = $Controller | ForEach-Object{ $_.ActiveSiteServices }
"ActiveSiteServices $ActiveSiteServices" | LogMe -display -progress
$tests.ActiveSiteServices = "NEUTRAL", $ActiveSiteServices
#==============================================================================================
# CHECK CPU AND MEMORY USAGE
#==============================================================================================
# Check the AvgCPU value for 5 seconds
$AvgCPUval = CheckCpuUsage ($ControllerDNS)
#$VDtests.LoadBalancingAlgorithm = "SUCCESS", "LB is set to BEST EFFORT"}
if( [int] $AvgCPUval -lt 75) { "CPU usage is normal [ $AvgCPUval % ]" | LogMe -display; $tests.AvgCPU = "SUCCESS", "$AvgCPUval %" }
elseif([int] $AvgCPUval -lt 85) { "CPU usage is medium [ $AvgCPUval % ]" | LogMe -warning; $tests.AvgCPU = "WARNING", "$AvgCPUval %" }
elseif([int] $AvgCPUval -lt 95) { "CPU usage is high [ $AvgCPUval % ]" | LogMe -error; $tests.AvgCPU = "ERROR", "$AvgCPUval %" }
elseif([int] $AvgCPUval -eq 101) { "CPU usage test failed" | LogMe -error; $tests.AvgCPU = "ERROR", "Err" }
else { "CPU usage is Critical [ $AvgCPUval % ]" | LogMe -error; $tests.AvgCPU = "ERROR", "$AvgCPUval %" }
$AvgCPUval = 0
# Check the Physical Memory usage
$UsedMemory = CheckMemoryUsage ($ControllerDNS)
if( $UsedMemory -lt 75) { "Memory usage is normal [ $UsedMemory % ]" | LogMe -display; $tests.MemUsg = "SUCCESS", "$UsedMemory %" }
elseif( [int] $UsedMemory -lt 85) { "Memory usage is medium [ $UsedMemory % ]" | LogMe -warning; $tests.MemUsg = "WARNING", "$UsedMemory %" }
elseif( [int] $UsedMemory -lt 95) { "Memory usage is high [ $UsedMemory % ]" | LogMe -error; $tests.MemUsg = "ERROR", "$UsedMemory %" }
elseif( [int] $UsedMemory -eq 101) { "Memory usage test failed" | LogMe -error; $tests.MemUsg = "ERROR", "Err" }
else { "Memory usage is Critical [ $UsedMemory % ]" | LogMe -error; $tests.MemUsg = "ERROR", "$UsedMemory %" }
$UsedMemory = 0
foreach ($disk in $diskLettersControllers)
{
# Check Disk Usage
$HardDisk = CheckHardDiskUsage -hostname $ControllerDNS -deviceID "$($disk):"
if ($null -ne $HardDisk) {
$XAPercentageDS = $HardDisk.PercentageDS
$frSpace = $HardDisk.frSpace
If ( [int] $XAPercentageDS -gt 15) { "Disk Free is normal [ $XAPercentageDS % ]" | LogMe -display; $tests."$($disk)Freespace" = "SUCCESS", "$frSpace GB" }
ElseIf ([int] $XAPercentageDS -eq 0) { "Disk Free test failed" | LogMe -error; $tests."$($disk)Freespace" = "ERROR", "Err" }
ElseIf ([int] $XAPercentageDS -lt 5) { "Disk Free is Critical [ $XAPercentageDS % ]" | LogMe -error; $tests."$($disk)Freespace" = "ERROR", "$frSpace GB" }
ElseIf ([int] $XAPercentageDS -lt 15) { "Disk Free is Low [ $XAPercentageDS % ]" | LogMe -warning; $tests."$($disk)Freespace" = "WARNING", "$frSpace GB" }
Else { "Disk Free is Critical [ $XAPercentageDS % ]" | LogMe -error; $tests."$($disk)Freespace" = "ERROR", "$frSpace GB" }
$XAPercentageDS = 0
$frSpace = 0
$HardDisk = $null
}
}
# Check uptime (Query over WMI)
$tests.WMI = "ERROR","Error"
try { $wmi=Get-WmiObject -class Win32_OperatingSystem -computer $ControllerDNS }
catch { $wmi = $null }
# Perform WMI related checks
if ($null -ne $wmi) {
$tests.WMI = "SUCCESS", "Success"
$LBTime=$wmi.ConvertToDateTime($wmi.Lastbootuptime)
[TimeSpan]$uptime=New-TimeSpan $LBTime $(get-date)
if ($uptime.days -lt $minUpTimeDaysDDC){
"reboot warning, last reboot: {0:D}" -f $LBTime | LogMe -display -warning
$tests.Uptime = "WARNING", (ToHumanReadable($uptime))
}
else { $tests.Uptime = "SUCCESS", (ToHumanReadable($uptime)) }
}
else { "WMI connection failed - check WMI for corruption" | LogMe -display -error }
}
" --- " | LogMe -display -progress
#Fill $tests into array
$ControllerResults.$ControllerDNS = $tests
}
#== Catalog Check ============================================================================================
"Check Catalog #################################################################################" | LogMe -display -progress
" " | LogMe -display -progress
$CatalogResults = @{}
$Catalogs = Get-BrokerCatalog -AdminAddress $AdminAddress
foreach ($Catalog in $Catalogs) {
$tests = @{}
#Name of MachineCatalog
$CatalogName = $Catalog | ForEach-Object{ $_.Name }
"Catalog: $CatalogName" | LogMe -display -progress
if ($ExcludedCatalogs -contains $CatalogName) {
"Excluded Catalog, skipping" | LogMe -display -progress
} else {
#CatalogAssignedCount
$CatalogAssignedCount = $Catalog | ForEach-Object{ $_.AssignedCount }
"Assigned: $CatalogAssignedCount" | LogMe -display -progress
$tests.AssignedToUser = "NEUTRAL", $CatalogAssignedCount
#CatalogUnassignedCount
$CatalogUnAssignedCount = $Catalog | ForEach-Object{ $_.UnassignedCount }
"Unassigned: $CatalogUnAssignedCount" | LogMe -display -progress
$tests.NotToUserAssigned = "NEUTRAL", $CatalogUnAssignedCount
# Assigned to DeliveryGroup
$CatalogUsedCountCount = $Catalog | ForEach-Object{ $_.UsedCount }
"Used: $CatalogUsedCountCount" | LogMe -display -progress
$tests.AssignedToDG = "NEUTRAL", $CatalogUsedCountCount
#MinimumFunctionalLevel
$MinimumFunctionalLevel = $Catalog | ForEach-Object{ $_.MinimumFunctionalLevel }
"MinimumFunctionalLevel: $MinimumFunctionalLevel" | LogMe -display -progress
$tests.MinimumFunctionalLevel = "NEUTRAL", $MinimumFunctionalLevel
#ProvisioningType
$CatalogProvisioningType = $Catalog | ForEach-Object{ $_.ProvisioningType }
"ProvisioningType: $CatalogProvisioningType" | LogMe -display -progress
$tests.ProvisioningType = "NEUTRAL", $CatalogProvisioningType
#AllocationType
$CatalogAllocationType = $Catalog | ForEach-Object{ $_.AllocationType }
"AllocationType: $CatalogAllocationType" | LogMe -display -progress
$tests.AllocationType = "NEUTRAL", $CatalogAllocationType
#UsedMcsSnapshot
$UsedMcsSnapshot = ""
$MCSInfo.MasterImageVM = ""
$CatalogProvisioningSchemeId = $Catalog | ForEach-Object{ $_.ProvisioningSchemeId }
"ProvisioningSchemeId: $CatalogProvisioningSchemeId " | LogMe -display -progress
$MCSInfo = (Get-ProvScheme -ProvisioningSchemeUid $CatalogProvisioningSchemeId)
$UsedMcsSnapshot = $MCSInfo.MasterImageVM
#"MasterImageVM: $MCSInfo.MasterImageVM"
$UsedMcsSnapshot = $UsedMcsSnapshot.trimstart("XDHyp:\HostingUnits\") = $MCSInfo.MasterImageVM
$UsedMcsSnapshot = $UsedMcsSnapshot.trimend(".template")
"UsedMcsSnapshot: = $UsedMcsSnapshot"
$tests.UsedMcsSnapshot = "NEUTRAL", $UsedMcsSnapshot
"", ""
$CatalogResults.$CatalogName = $tests
}
" --- " | LogMe -display -progress
}
#== DeliveryGroups Check ============================================================================================
"Check Assigments #############################################################################" | LogMe -display -progress
" " | LogMe -display -progress
$AssigmentsResults = @{}
$Assigments = Get-BrokerDesktopGroup -AdminAddress $AdminAddress
foreach ($Assigment in $Assigments) {
$tests = @{}
#Name of DeliveryGroup
$DeliveryGroup = $Assigment | ForEach-Object{ $_.Name }
"DeliveryGroup: $DeliveryGroup" | LogMe -display -progress
if ($ExcludedCatalogs -contains $DeliveryGroup) {
"Excluded Delivery Group, skipping" | LogMe -display -progress
} else {
#PublishedName
$AssigmentDesktopPublishedName = $Assigment | ForEach-Object{ $_.PublishedName }
"PublishedName: $AssigmentDesktopPublishedName" | LogMe -display -progress
$tests.PublishedName = "NEUTRAL", $AssigmentDesktopPublishedName
#DesktopsTotal
$TotalDesktops = $Assigment | ForEach-Object{ $_.TotalDesktops }
"DesktopsAvailable: $TotalDesktops" | LogMe -display -progress
$tests.TotalMachines = "NEUTRAL", $TotalDesktops
#DesktopsAvailable
$AssigmentDesktopsAvailable = $Assigment | ForEach-Object{ $_.DesktopsAvailable }
"DesktopsAvailable: $AssigmentDesktopsAvailable" | LogMe -display -progress
$tests.DesktopsAvailable = "NEUTRAL", $AssigmentDesktopsAvailable
#DesktopKind
$AssigmentDesktopsKind = $Assigment | ForEach-Object{ $_.DesktopKind }
"DesktopKind: $AssigmentDesktopsKind" | LogMe -display -progress
$tests.DesktopKind = "NEUTRAL", $AssigmentDesktopsKind
#SessionSupport
$SessionSupport = $Assigment | ForEach-Object{ $_.SessionSupport }
"SessionSupport: $SessionSupport" | LogMe -display -progress
$tests.SessionSupport = "NEUTRAL", $SessionSupport
#ShutdownAfterUse
$ShutdownDesktopsAfterUse = $Assigment | ForEach-Object{ $_.ShutdownDesktopsAfterUse }
"ShutdownDesktopsAfterUse: $ShutdownDesktopsAfterUse" | LogMe -display -progress
if ($SessionSupport -eq "MultiSession" -and $ShutdownDesktopsAfterUse -eq "$true" ) {
$tests.ShutdownAfterUse = "ERROR", $ShutdownDesktopsAfterUse
}
else {
$tests.ShutdownAfterUse = "NEUTRAL", $ShutdownDesktopsAfterUse
}
#MinimumFunctionalLevel
$MinimumFunctionalLevel = $Assigment | ForEach-Object{ $_.MinimumFunctionalLevel }
"MinimumFunctionalLevel: $MinimumFunctionalLevel" | LogMe -display -progress
$tests.MinimumFunctionalLevel = "NEUTRAL", $MinimumFunctionalLevel
if ($SessionSupport -eq "MultiSession" ) {
$tests.DesktopsFree = "NEUTRAL", "N/A"
$tests.DesktopsInUse = "NEUTRAL", "N/A"
}
else {
#DesktopsInUse
$AssigmentDesktopsInUse = $Assigment | ForEach-Object{ $_.DesktopsInUse }
"DesktopsInUse: $AssigmentDesktopsInUse" | LogMe -display -progress
$tests.DesktopsInUse = "NEUTRAL", $AssigmentDesktopsInUse
#DesktopFree
$AssigmentDesktopsFree = $AssigmentDesktopsAvailable - $AssigmentDesktopsInUse
"DesktopsFree: $AssigmentDesktopsFree" | LogMe -display -progress
if ($AssigmentDesktopsKind -eq "shared") {
if ($AssigmentDesktopsFree -gt 0 ) {
"DesktopsFree < 1 ! ($AssigmentDesktopsFree)" | LogMe -display -progress
$tests.DesktopsFree = "SUCCESS", $AssigmentDesktopsFree
} elseif ($AssigmentDesktopsFree -lt 0 ) {
"DesktopsFree < 1 ! ($AssigmentDesktopsFree)" | LogMe -display -progress
$tests.DesktopsFree = "SUCCESS", "N/A"
} else {
$tests.DesktopsFree = "WARNING", $AssigmentDesktopsFree
"DesktopsFree > 0 ! ($AssigmentDesktopsFree)" | LogMe -display -progress
}
} else {
$tests.DesktopsFree = "NEUTRAL", "N/A"
}
}
#inMaintenanceMode
$AssigmentDesktopsinMaintenanceMode = $Assigment | ForEach-Object{ $_.inMaintenanceMode }
"inMaintenanceMode: $AssigmentDesktopsinMaintenanceMode" | LogMe -display -progress
if ($AssigmentDesktopsinMaintenanceMode) { $tests.MaintenanceMode = "WARNING", "ON" }
else { $tests.MaintenanceMode = "SUCCESS", "OFF" }
#DesktopsUnregistered
$AssigmentDesktopsUnregistered = $Assigment | ForEach-Object{ $_.DesktopsUnregistered }
"DesktopsUnregistered: $AssigmentDesktopsUnregistered" | LogMe -display -progress
if ($AssigmentDesktopsUnregistered -gt 0 ) {
"DesktopsUnregistered > 0 ! ($AssigmentDesktopsUnregistered)" | LogMe -display -progress
$tests.DesktopsUnregistered = "WARNING", $AssigmentDesktopsUnregistered
} else {
$tests.DesktopsUnregistered = "SUCCESS", $AssigmentDesktopsUnregistered
"DesktopsUnregistered <= 0 ! ($AssigmentDesktopsUnregistered)" | LogMe -display -progress
}
#Fill $tests into array
$AssigmentsResults.$DeliveryGroup = $tests
}
" --- " | LogMe -display -progress
}
# ======= License Check ========
if($ShowCTXLicense -eq 1 ){
$myCollection = @()
try
{
$LicWMIQuery = get-wmiobject -namespace "ROOT\CitrixLicensing" -computer $lsname -query "select * from Citrix_GT_License_Pool" -ErrorAction Stop | ? {$_.PLD -in $CTXLicenseMode}
foreach ($group in $($LicWMIQuery | group pld))
{
$lics = $group | Select-Object -ExpandProperty group
$i = 1
$myArray_Count = 0
$myArray_InUse = 0
$myArray_Available = 0
foreach ($lic in @($lics))
{
$myArray = "" | Select-Object LicenseServer,LicenceName,Count,InUse,Available
$myArray.LicenseServer = $lsname
$myArray.LicenceName = "$($lics.pld) ($i) Licence"
$myArray.Count = $Lic.count - $Lic.Overdraft
if ($Lic.inusecount -gt $myArray.Count) {$myArray.InUse = $myArray.Count} else {$myArray.InUse = $Lic.inusecount}
$myArray.Available = $myArray.count - $myArray.InUse
$myCollection += $myArray
$myArray = "" | Select-Object LicenseServer,LicenceName,Count,InUse,Available
$myArray.LicenseServer = $lsname
$myArray.LicenceName = "$($lics.pld) ($i) Overdraft"
$myArray.Count = $Lic.Overdraft
if ($Lic.inusecount -gt $($Lic.count - $Lic.Overdraft)) {$myArray.InUse = $Lic.inusecount - $($Lic.count - $Lic.Overdraft)} else {$myArray.InUse = 0}
$myArray.Available = $myArray.count - $myArray.InUse
$myCollection += $myArray
$myArray_Count += $Lic.count
$myArray_InUse += $Lic.inusecount
$myArray_Available += $Lic.pooledavailable
$i++
}
$myArray = "" | Select-Object LicenseServer,LicenceName,Count,InUse,Available
$myArray.LicenseServer = $lsname
$myArray.LicenceName = "$($lics.pld) - Total"
$myArray.Count = $myArray_Count
$myArray.InUse = $myArray_InUse
$myArray.Available = $myArray_Available
$myCollection += $myArray
}
}
catch
{
$myArray = "" | Select-Object LicenseServer,LicenceName,Count,InUse,Available
$myArray.LicenseServer = $lsname
$myArray.LicenceName = "n/a"
$myArray.Count = "n/a"
$myArray.InUse = "n/a"
$myArray.Available = "n/a"
$myCollection += $myArray
}
$CTXLicResults = @{}
foreach ($line in $myCollection)
{
$tests = @{}
if ($line.LicenceName -eq "n/a")
{
$tests.LicenseServer ="error", $line.LicenseServer
$tests.Count ="error", $line.Count
$tests.InUse ="error", $line.InUse
$tests.Available ="error", $line.Available
}
else
{
$tests.LicenseServer ="NEUTRAL", $line.LicenseServer
$tests.Count ="NEUTRAL", $line.Count
$tests.InUse ="NEUTRAL", $line.InUse
$tests.Available ="NEUTRAL", $line.Available}
$CTXLicResults.($line.LicenceName) = $tests
}
}
else {"CTX License Check skipped because ShowCTXLicense = 0 " | LogMe -display -progress }
# ======= Desktop Check ========
"Check virtual Desktops ####################################################################################" | LogMe -display -progress
" " | LogMe -display -progress
if($ShowDesktopTable -eq 1 ) {
$allResults = @{}
$machines = Get-BrokerMachine -MaxRecordCount $maxmachines -AdminAddress $AdminAddress| Where-Object {$_.SessionSupport -eq "SingleSession" -and @(Compare-Object $_.tags $ExcludedTags -IncludeEqual | Where-Object {$_.sideindicator -eq '=='}).count -eq 0 -and $_.catalogname -notin $ExcludedCatalogs}
# SessionSupport only availiable in XD 7.x - for this reason only distinguish in Version above 7 if Desktop or XenApp
if($controllerversion -lt 7 ) { $machines = Get-BrokerMachine -MaxRecordCount $maxmachines -AdminAddress $AdminAddress -and @(Compare-Object $_.tags $ExcludedTags -IncludeEqual | Where-Object {$_.sideindicator -eq '=='}).count -eq 0 -and $_.catalogname -notin $ExcludedCatalogs}
else { $machines = Get-BrokerMachine -MaxRecordCount $maxmachines -AdminAddress $AdminAddress| Where-Object {$_.SessionSupport -eq "SingleSession" -and @(Compare-Object $_.tags $ExcludedTags -IncludeEqual | Where-Object {$_.sideindicator -eq '=='}).count -eq 0 -and $_.catalogname -notin $ExcludedCatalogs} }
$Maintenance = Get-CitrixMaintenanceInfo -AdminAddress $AdminAddress
foreach($machine in $machines) {
$tests = @{}
$ErrorVDI = 0
# Column Name of Desktop
$machineDNS = $machine | ForEach-Object{ $_.DNSName }
"Machine: $machineDNS" | LogMe -display -progress
# Column CatalogName
$CatalogName = $machine | ForEach-Object{ $_.CatalogName }
"Catalog: $CatalogName" | LogMe -display -progress
$tests.CatalogName = "NEUTRAL", $CatalogName