provider/vcomputer/Get-IcingaVirtualComputerInfo.psm1

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
<#
.SYNOPSIS
    This function is the basic provider for fetching virtual computer information from Hyper-V systems and collects virtual machine, snapshot and virtual switch data.
    Plugins requiring at least two of the mentioned data together, should use this data provider.
.DESCRIPTION
    This function is the basic provider for fetching virtual computer information from Hyper-V systems and collects virtual machine, snapshot and virtual switch data.
    Plugins requiring at least two of the mentioned data together, should use this data provider.
.OUTPUTS
    System.Hashtable
.ROLE
    ### WMI Permissions

    * Root\Virtualization\v2
    * Root\Cimv2

    ### Performance Counter

    * Processor(*)\% processor time

    ### Required User Groups

    * Performance Monitor Users
    * Hyper-V Administrator
.PARAMETER IncludeVms
    Include only virtual machines with a specific name. Supports wildcard usage (*)
.PARAMETER ExcludeVms
    Exclude virtual machines with a specific name. Supports wildcard usage (*)
.PARAMETER ActiveVms
    Include only virtual machines that are currently running
.Link
    https://github.com/Icinga/icinga-powershell-hyperv
#>


function Get-IcingaVirtualComputerInfo()
{
    param (
        [array]$IncludeVms = @(),
        [array]$ExcludeVms = @(),
        [Switch]$ActiveVms = $FALSE
    );

    # Get all information about the hyperv virtual Computers
    $VirtualComputers       = Get-IcingaWindowsInformation -ClassName Msvm_SummaryInformation -Namespace 'Root\Virtualization\v2';
    # Gather all information regarding virtual computers memory allocation
    $VComputerMemorys       = Get-IcingaWindowsInformation -ClassName Msvm_MemorySettingData -Namespace 'Root\Virtualization\v2';
    # Get infos about virtual computers hard disk drive / VHDs
    $VcomputerVHDs          = Get-IcingaWindowsInformation -ClassName Msvm_LogicalDisk -Namespace 'Root\Virtualization\v2';
    $VComputerHardDisks     = Get-IcingaPhysicalDiskInfo;
    # Get the Partition where all virtual Computers are Stored
    $VmPartitionsPath       = Get-IcingaWindowsInformation -ClassName Msvm_StorageAllocationSettingData -Namespace 'Root\Virtualization\v2';
    # Gather all infos rgarding Virtual Computer CPU used
    $CountCPUCores          = Get-IcingaCPUCount;
    $VComputerRamLimit      = (Get-IcingaMemoryPerformanceCounter).'Memory Total Bytes';
    $PluginInstalled        = $FALSE;
    $CurrentVmsUsage        = 0;
    [array]$AccessDeniedVms = @();
    $VComputerData          = @{
        'VMs'       = @{ };
        'Summary'   = @{
            'RunningVms'      = 0;
            'StoppedVms'      = 0;
            'TotalVms'        = 0;
            'AccessDeniedVms' = '';
        };
        'Resources' = @{
            'RAMOverCommit'     = @{
                'Bytes'    = 0;
                'Percent'  = 0;
                'Capacity' = $VComputerRamLimit;
            };
            'CPUOverCommit'     = @{
                'Percent'   = 0;
                'Cores'     = 0;
                'Available' = $CountCPUCores;
            };
            'StorageOverCommit' = @{ };
        };
    };

    if (-Not (Test-IcingaHyperVInstalled)) {
        Exit-IcingaThrowException -ExceptionType 'Custom' -CustomMessage 'Hyperv not installed' -ExceptionThrown 'The Hyper-V feature is not installed on this system.' -Force;
        return $VComputerData;
    }

    $VMMSService = (Get-IcingaServices 'vmms').vmms;

    if ($null -eq $VMMSService -Or $VMMSService.configuration.Status.raw -ne $ProviderEnums.ServiceStatus.Running) {
        Exit-IcingaThrowException -ExceptionType 'Custom' -CustomMessage 'Service not running' -ExceptionThrown 'The required Hyper-V service "vmms" is not running.' -Force;
        return $VComputerData;
    }

    if ($null -eq $VirtualComputers) {
        return $VComputerData;
    }

    if (Test-IcingaFunction 'Get-IcingaClusterSharedVolumeData') {
        $PluginInstalled = $TRUE;
    }

    foreach ($vcomputer in $VirtualComputers) {
        # The basic information details about the virtual computers
        $details = @{
            'InstanceID'                      = $vcomputer.InstanceID;
            'AllocatedGPU'                    = $vcomputer.AllocatedGPU;
            'Shielded'                        = $vcomputer.Shielded;
            'AsynchronousTasks'               = $vcomputer.AsynchronousTasks;
            'CreationTime'                    = $vcomputer.CreationTime;
            'ElementName'                     = $vcomputer.ElementName;
            'EnabledState'                    = $vcomputer.EnabledState;
            'OtherEnabledState'               = $vcomputer.OtherEnabledState;
            'GuestOperatingSystem'            = $vcomputer.GuestOperatingSystem;
            'HealthState'                     = $vcomputer.HealthState;
            'Heartbeat'                       = $vcomputer.Heartbeat;
            'MemoryUsage'                     = $vcomputer.MemoryUsage;
            'MemoryAvailable'                 = $vcomputer.MemoryAvailable;
            'AvailableMemoryBuffer'           = $vcomputer.AvailableMemoryBuffer;
            'SwapFilesInUse'                  = $vcomputer.SwapFilesInUse;
            'Name'                            = $vcomputer.Name;
            'NumberOfProcessors'              = $vcomputer.NumberOfProcessors;
            'OperationalStatus'               = $vcomputer.OperationalStatus;
            'ProcessorLoad'                   = $vcomputer.ProcessorLoad;
            'ProcessorLoadHistory'            = $vcomputer.ProcessorLoadHistory;
            'Snapshots'                       = @{
                'Latest' = $null;
                'List'   = @();
                'Info'   = @{ };
            };
            'StatusDescriptions'              = $vcomputer.StatusDescriptions;
            'ThumbnailImage'                  = $vcomputer.ThumbnailImage;
            'ThumbnailImageHeight'            = $vcomputer.ThumbnailImageHeight;
            'ThumbnailImageWidth'             = $vcomputer.ThumbnailImageWidth;
            'UpTime'                          = $vcomputer.UpTime;
            'ReplicationState'                = $vcomputer.ReplicationState;
            'ReplicationStateEx'              = $vcomputer.ReplicationStateEx;
            'ReplicationHealth'               = $vcomputer.ReplicationHealth;
            'ReplicationHealthEx'             = $vcomputer.ReplicationHealthEx;
            'ReplicationMode'                 = $vcomputer.ReplicationMode;
            'TestReplicaSystem'               = @{ };
            'ApplicationHealth'               = $vcomputer.ApplicationHealth;
            'IntegrationServicesVersionState' = $vcomputer.IntegrationServicesVersionState;
            'MemorySpansPhysicalNumaNodes'    = $vcomputer.MemorySpansPhysicalNumaNodes;
            'ReplicationProviderId'           = $vcomputer.ReplicationProviderId;
            'EnhancedSessionModeState'        = $vcomputer.EnhancedSessionModeState;
            'VirtualSwitches'                 = $vcomputer.VirtualSwitchNames;
            'VirtualSystemSubType'            = $vcomputer.VirtualSystemSubType;
            'HostComputerSystemName'          = $vcomputer.HostComputerSystemName;
        };

        # Verify that the virtual computer TestReplicaSystem attribute is not null
        # otherwise we cannot access the following information, which we require
        if ($null -ne $vcomputer.TestReplicaSystem) {
            foreach ($testreplica in $vcomputer.TestReplicaSystem) {
                $details.TestReplicaSystem = @{
                    'Count'                                    = $testreplica.__PROPERTY_COUNT;
                    'AvailableRequestedStates'                 = $testreplica.AvailableRequestedStates;
                    'Caption'                                  = $testreplica.Caption;
                    'CommunicationStatus'                      = $testreplica.CommunicationStatus;
                    'Description'                              = $testreplica.Description;
                    'DetailedStatus'                           = $testreplica.DetailedStatus;
                    'ElementName'                              = $testreplica.ElementName;
                    'EnabledDefault'                           = $testreplica.EnabledDefault;
                    'EnabledState'                             = $testreplica.EnabledState;
                    'EnhancedSessionModeState'                 = $testreplica.EnhancedSessionModeState;
                    'FailedOverReplicationType'                = $testreplica.FailedOverReplicationType;
                    'HealthState'                              = $testreplica.HealthState;
                    'InstallDate'                              = $testreplica.InstallDate;
                    'LastApplicationConsistentReplicationTime' = $testreplica.LastApplicationConsistentReplicationTime;
                    'LastReplicationTime'                      = $testreplica.LastReplicationTime;
                    'LastReplicationType'                      = $testreplica.LastReplicationType;
                    'LastSuccessfulBackupTime'                 = $testreplica.LastSuccessfulBackupTime;
                    'Name'                                     = $testreplica.Name;
                    'NumberOfNumaNodes'                        = $testreplica.NumberOfNumaNodes;
                    'OnTimeInMilliseconds'                     = $testreplica.OnTimeInMilliseconds;
                    'PrimaryOwnerContact'                      = $testreplica.PrimaryOwnerContact;
                    'PrimaryOwnerName'                         = $testreplica.PrimaryOwnerName;
                    'PrimaryStatus'                            = $testreplica.PrimaryStatus;
                    'ProcessID'                                = $testreplica.ProcessID;
                    'ReplicationHealth'                        = $testreplica.ReplicationHealth;
                    'ReplicationMode'                          = $testreplica.ReplicationMode;
                    'ReplicationState'                         = $testreplica.ReplicationState;
                    'RequestedState'                           = $testreplica.RequestedState;
                    'ResetCapability'                          = $testreplica.ResetCapability;
                    'Roles'                                    = $testreplica.Roles;
                    'Status'                                   = $testreplica.Status;
                    'TimeOfLastConfigurationChange'            = $testreplica.TimeOfLastConfigurationChange;
                    'TimeOfLastStateChange'                    = $testreplica.TimeOfLastStateChange;
                    'TransitioningToState'                     = $testreplica.TransitioningToState;
                };
            }
        }

        $LatestSnapshot = @{ };
        # We iterate through all available virtual computer snapshots
        foreach ($snapshot in $vcomputer.Snapshots) {
            [string]$SnapshotPart = $snapshot.ConfigurationDataRoot;
            $SnapshotPart         = $SnapshotPart.Split('\')[0];
            $SnapshotContent      = @{
                'AssociatedResourcePool'               = $snapshot.AssociatedResourcePool;
                'AutomaticRecoveryAction'              = $snapshot.AutomaticRecoveryAction;
                'AutomaticShutdownAction'              = $snapshot.AutomaticShutdownAction;
                'AutomaticStartupAction'               = $snapshot.AutomaticStartupAction;
                'AutomaticStartupActionDelay'          = $snapshot.AutomaticStartupActionDelay;
                'AutomaticStartupActionSequenceNumber' = $snapshot.AutomaticStartupActionSequenceNumber;
                'BandwidthReservationMode'             = $snapshot.BandwidthReservationMode;
                'Caption'                              = $snapshot.Caption;
                'ExtensionOrder'                       = $snapshot.ExtensionOrder;
                'ConfigurationDataRoot'                = $snapshot.ConfigurationDataRoot;
                'ConfigurationFile'                    = $snapshot.ConfigurationFile;
                'ConfigurationID'                      = $snapshot.ConfigurationID;
                'InstanceID'                           = $snapshot.InstanceID;
                'CreationTime'                         = $snapshot.CreationTime;
                'IOVPreferred'                         = $snapshot.IOVPreferred;
                'LogDataRoot'                          = $snapshot.LogDataRoot;
                'MaxNumMACAddress'                     = $snapshot.MaxNumMACAddress;
                'Description'                          = $snapshot.Description;
                'ElementName'                          = $snapshot.ElementName;
                'Notes'                                = $snapshot.Notes;
                'PacketDirectEnabled'                  = $snapshot.PacketDirectEnabled;
                'RecoveryFile'                         = $snapshot.RecoveryFile;
                'SnapshotDataRoot'                     = $snapshot.SnapshotDataRoot;
                'SwapFileDataRoot'                     = $snapshot.SwapFileDataRoot;
                'TeamingEnabled'                       = $snapshot.TeamingEnabled;
                'VirtualSystemIdentifier'              = $snapshot.VirtualSystemIdentifier;
                'VirtualSystemType'                    = $snapshot.VirtualSystemType;
                'VLANConnection'                       = $snapshot.VLANConnection;
                'HighMmioGapSize'                      = $snapshot.HighMmioGapSize;
                'LowMmioGapSize'                       = $snapshot.LowMmioGapSize;
                'VirtualNumaEnabled'                   = $snapshot.VirtualNumaEnabled;
                'IsSaved'                              = $snapshot.IsSaved;
                'Partition'                            = $SnapshotPart;
                'Path'                                 = ([string]::Format('{0}{1}{2}', $snapshot.ConfigurationDataRoot, '\', $snapshot.ConfigurationFile));
            };

            if (Test-Path $SnapshotContent.Path) {
                $SnapshotSize = Get-ChildItem -Path $SnapshotContent.Path | Select-Object Length;
                $SnapshotContent.Add('Error', $null);
            } else {
                $SnapshotSize = @{ 'Length' = 0};
                $SnapshotContent.Add('Error', 'PermissionDenied');
            }

            $SnapshotContent.Add('Size', $SnapshotSize.Length);

            if ($details.Snapshots.Info.ContainsKey($SnapshotPart) -eq $FALSE) {
                $details.Snapshots.Info.Add($SnapshotPart, @{
                        'TotalUsed' = $SnapshotSize.Length;
                    }
                );
            } else {
                $details.Snapshots.Info[$SnapshotPart].TotalUsed += $SnapshotSize.Length;
            }

            if ([datetime]$snapshot.CreationTime -gt $LatestSnapshot.CreationTime) {
                # Here comes always only the latest snapshot
                $details.Snapshots.Latest = $SnapshotContent;
            }

            $LatestSnapshot = $snapshot;
            # Here we only add snapshots that are no longer current
            $details.Snapshots.List += $SnapshotContent;

            foreach ($disk in $VComputerHardDisks.Keys) {
                $PhysicalDisk = $VComputerHardDisks[$disk];
                if ($PhysicalDisk.DriveReference.ContainsKey($SnapshotPart) -eq $FALSE) {
                    continue;
                }

                [string]$DiskId = $PhysicalDisk.DriveReference[$SnapshotPart];
                $FreeSpace      = $PhysicalDisk.PartitionLayout[$DiskId].FreeSpace;
                $PartSize       = $PhysicalDisk.PartitionLayout[$DiskId].Size;

                if ($details.Snapshots.Info[$SnapshotPart].ContainsKey('FreeSpace') -eq $FALSE) {
                    $details.Snapshots.Info[$SnapshotPart].Add('FreeSpace', $FreeSpace);
                }

                if ($details.Snapshots.Info[$SnapshotPart].ContainsKey('Size') -eq $FALSE) {
                    $details.Snapshots.Info[$SnapshotPart].Add('Size', $PartSize);
                }

                break;
            }
        }

        # Sort our Snapshots based on the creation Time
        $details.Snapshots.List = $details.Snapshots.List | Sort-Object -Property @{Expression = { [datetime]$_.CreationTime }; Descending = $TRUE };

        # We are going to loop through all available vm partitions
        foreach ($vmPartition in $VmPartitionsPath) {
            # We filter out the drive letter where the VMs are stored
            [string]$vmPath     = $vmPartition.HostResource;
            $vmPath             = ([string]::Format('{0}{1}', ($vmPath.Replace('{', '').Split(':')[0]), ':'));
            # Wi filter out the InstanceID for comparing with the vm Id
            [string]$InstanceID = $vmPartition.InstanceID;
            $InstanceID         = $InstanceID.Split(':')[1].Split('\')[0];

            # Skip the loop if the InstanceID doesn't match
            if ($InstanceID -ne $vcomputer.Name) {
                continue;
            }

            # Add some details of the vm partition
            $details += @{
                'Caption'               = $vmPartition.Caption;
                'VMInstanceID'          = $vmPartition.InstanceID;
                'AutomaticAllocation'   = $vmPartition.AutomaticAllocation;
                'AutomaticDeallocation' = $vmPartition.AutomaticDeallocation;
                'HostResource'          = $vmPartition.HostResource;
                'Partition'             = $vmPath;
                'CurrentUsage'          = 'PermissionDenied';
            };

            if (Test-Path -Path ([string]$vmPartition.HostResource)) {
                $details.CurrentUsage = (Get-Item -Path ([string]$vmPartition.HostResource) | Select-Object Length).Length;
            }

            # If the partition doesn't exist in StorageOverCommit hashtable then add ones
            if ($VComputerData.Resources.StorageOverCommit.ContainsKey($vmPath) -eq $FALSE) {
                $VComputerData.Resources.StorageOverCommit += @{
                    $vmPath = @{
                        'Bytes'    = 0;
                        'Percent'  = 0;
                        'Capacity' = 0;
                    }
                };
            }

            break;
        }

        # Calculate Hyper-V-Server overcommitment RAM, overcommitment CPU and overcommitment memory
        if ($vcomputer.EnabledState -ne $HypervProviderEnums.VMEnabledStateName.Disabled) {
            # Calculation for RAM Overcommitment
            foreach ($memory in $VComputerMemorys) {
                [string]$InstanceId = $memory.InstanceID;
                $InstanceId         = $InstanceId.Split(':')[1].Split('\')[0];

                if ($vcomputer.Name -ne $InstanceId) {
                    continue;
                }

                $details.Add('DynamicMemoryAllocated', $memory.DynamicMemoryEnabled);

                if ($memory.DynamicMemoryEnabled) {
                    $VComputerData.Resources.RAMOverCommit.Bytes += $memory.Limit;
                    $details.Add('MemoryCapacity', $memory.Limit);
                } else {
                    $VComputerData.Resources.RAMOverCommit.Bytes += $memory.VirtualQuantity;
                    $details.Add('MemoryCapacity', $memory.VirtualQuantity);
                }
            }

            # Calculation for CPU Overcommitment
            $VComputerData.Resources.CPUOverCommit.Cores += $vcomputer.NumberOfProcessors;

            # Calculation for vms Storage Overcommitment
            foreach ($vhd in $VcomputerVHDs) {
                if ($vhd.SystemName -ne $vcomputer.Name) {
                    continue;
                }

                if ($details.ContainsKey('DiskCapacity') -eq $FALSE) {
                    $details.Add('DiskCapacity', ($vhd.BlockSize * $vhd.NumberOfBlocks));
                }

                [string]$DeviceID = $vhd.DeviceId;
                $DeviceID         = $DeviceID.Split(':')[1].Split('\')[0];
                if ($details.ContainsKey('DeviceID') -eq $FALSE) {
                    $details.Add('DeviceID', $DeviceID);
                }

                # Gather informations about the virtual computers hard disk drive
                $VComputerData.Resources.StorageOverCommit[$details.Partition].Bytes += ($details.DiskCapacity);
            }

            if ($details.CurrentUsage -ne 'PermissionDenied') {
                $CurrentVmsUsage += $details.CurrentUsage;
            } else {
                $AccessDeniedVms += $vcomputer.ElementName;
            }

            # we count up here to get the total number of vms that are still running
            $VComputerData.Summary.RunningVms++;
        } else {
            # we count up here to get the number of total vms that have not yet started
            $VComputerData.Summary.StoppedVms++;
        }

        if ($ActiveVms -And $vcomputer.EnabledState -eq $HypervProviderEnums.VMEnabledStateName.Disabled) {
            continue;
        }

        [bool]$RegexMatch = $TRUE;
        # We have to skip the loop if the regex doesn't match
        if ($IncludeVms.Count -ne 0) {
            foreach ($item in $IncludeVms) {
                if ([string]$vcomputer.ElementName -like [string]$item) {
                    $RegexMatch = $FALSE;
                    break;
                }
            }

            if ($RegexMatch) {
                continue;
            }
        }

        # We have to skip the loop if the regex matches with the element name
        if ($ExcludeVms.Count -ne 0) {
            [bool]$RegexMatch = $FALSE;
            foreach ($item in $ExcludeVms) {
                if ([string]$vcomputer.ElementName -like [string]$item) {
                    $RegexMatch = $TRUE;
                    break;
                }
            }

            if ($RegexMatch) {
                continue;
            }
        }

        foreach ($VchardDisk in $VComputerHardDisks.Keys) {
            $OvercommitCalculated = $FALSE;
            $PhysicalDisk         = $VComputerHardDisks[$VchardDisk];

            if ([string]::IsNullOrEmpty($details.Partition)) {
                continue;
            }

            if ($PhysicalDisk.DriveReference.ContainsKey($details.Partition) -eq $FALSE) {
                continue;
            }

            [string]$PartitionId = $PhysicalDisk.DriveReference[$details.Partition];

            # Gather informations about the virtual computers hard disk drive
            $PartitionSize = $PhysicalDisk.PartitionLayout[$PartitionId].Size;

            if ($CurrentVmsUsage -gt $PartitionSize) {
                if ($PluginInstalled -eq $FALSE) {
                    if ($VComputerData.Summary.ContainsKey('Located') -eq $FALSE) {
                        $VComputerData.Summary.Add('Located', 'ClusterStorage');
                    }
                } else {
                    $ClusterSharedVolume = Get-IcingaClusterSharedVolumeData;
                    foreach ($volume in $ClusterSharedVolume.Keys) {
                        $SharedVolume     = $ClusterSharedVolume[$volume];
                        [string]$VolumeId = $SharedVolume.SharedVolumeInfo.FriendlyVolumeName;
                        $VolumeId         = $VolumeId.Split('\')[0];

                        if ($VolumeId -ne $details.Partition) {
                            continue;
                        }

                        # Calculation of the average Storage overcommitment
                        $ConvertToPercent = ([System.Math]::Round(
                                (
                                    ($VComputerData.Resources.StorageOverCommit[$details.Partition].Bytes / $SharedVolume.SharedVolumeInfo.Partition.Size) * 100
                                ) - 100, 2
                            )
                        );

                        if ($ConvertToPercent -le 0) {
                            $ConvertToPercent = 0;
                        }

                        $VComputerData.Resources.StorageOverCommit[$details.Partition].Percent  = $ConvertToPercent;
                        $VComputerData.Resources.StorageOverCommit[$details.Partition].Capacity = $SharedVolume.SharedVolumeInfo.Partition.Size;

                        $OvercommitCalculated = $TRUE;
                        break;
                    }
                }
            }

            if ($OvercommitCalculated -eq $FALSE) {
                # Calculation of the average Storage overcommitment
                $ConvertToPercent = ([System.Math]::Round((($VComputerData.Resources.StorageOverCommit[$details.Partition].Bytes / $PartitionSize) * 100) - 100, 2));

                if ($ConvertToPercent -le 0) {
                    $ConvertToPercent = 0;
                }

                $VComputerData.Resources.StorageOverCommit[$details.Partition].Percent  = $ConvertToPercent;
                $VComputerData.Resources.StorageOverCommit[$details.Partition].Capacity = $PartitionSize;
            }

            break;
        }

        $VComputerData.VMs.Add($vcomputer.ElementName, $details);
    }

    if ($VComputerData.VMs.Count -eq 0) {
        return;
    }

    foreach ($vm in $VComputerData.VMs.Keys) {
        $virtualmachine = $VComputerData.VMs[$vm];
        if ($virtualmachine.Snapshots.Info.Count -eq 0) {
            continue;
        }

        foreach ($partition in $virtualmachine.Snapshots.Info.Keys) {
            $SnapshotPartition = $virtualmachine.Snapshots.Info[$partition];
            if ($SnapshotPartition.TotalUsed -lt $SnapshotPartition.FreeSpace) {
                continue;
            }

            if ($PluginInstalled -eq $FALSE) {
                if ($VComputerData.Summary.ContainsKey('SnapshotLocated') -eq $FALSE) {
                    $VComputerData.Summary.Add('SnapshotLocated', 'ClusterStorage');
                }
            } else {
                $ClusterSharedVolume = Get-IcingaClusterSharedVolumeData;
                foreach ($volume in $ClusterSharedVolume.Keys) {
                    $SharedVolume     = $ClusterSharedVolume[$volume];
                    [string]$VolumeId = $SharedVolume.SharedVolumeInfo.FriendlyVolumeName;
                    $VolumeId         = $VolumeId.Split('\')[0];

                    if ($partition -ne $VolumeId) {
                        continue;
                    }

                    $VComputerData.VMs[$vm].Snapshots.Info[$partition].FreeSpace = $SharedVolume.SharedVolumeInfo.Partition.FreeSpace;

                    break;
                }
            }
        }
    }

    # Calculate the average of Hyper-v CPU Cores used by the vms
    if ($null -eq $CountCPUCores) {
        $VComputerData.Resources.CPUOverCommit.Percent = 100;
    } else {
        $VComputerData.Resources.CPUOverCommit.Percent = ([System.Math]::Round((($VComputerData.Resources.CPUOverCommit.Cores / $CountCPUCores) * 100) - 100, 2));
    }

    $VComputerData.Summary.AccessDeniedVms = $AccessDeniedVms;
    # Here we calculate how many Vms the Hyper-V server has in total
    $VComputerData.Summary.TotalVms = ($VComputerData.Summary.RunningVms + $VComputerData.Summary.StoppedVms);
    # Calculate the average Hyper-V RAM Overcommitment
    $RAMUsedPercent = ([System.Math]::Round((($VComputerData.Resources.RAMOverCommit.Bytes / $VComputerRamLimit) * 100) - 100, 2));
    if ($RAMUsedPercent -le 0) {
        $RAMUsedPercent = 0;
    }

    $VComputerData.Resources.RAMOverCommit.Percent  = $RAMUsedPercent;
    $VComputerData.Resources.RAMOverCommit.Capacity = $VComputerRamLimit;

    return $VComputerData;
}