-
Notifications
You must be signed in to change notification settings - Fork 8
/
VMware.CloudFoundation.PowerManagement.psm1
2449 lines (2112 loc) · 125 KB
/
VMware.CloudFoundation.PowerManagement.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
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
# Copyright 2023-2024 Broadcom. All Rights Reserved.
# SPDX-License-Identifier: BSD-2
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
### Note
# This PowerShell module should be considered entirely experimental. It is still in development & not tested beyond
# lab scenarios. It is recommended you don't use it for any production environment without testing extensively!
# Enable communication with self-signed certificates when using Powershell Core if you require all communications to be secure
# and do not wish to allow communication with self-signed certificates remove lines 16-40 before importing the module.
# Enable self-signed certificates
if ($PSEdition -EQ 'Core') {
$PSDefaultParameterValues.Add("Invoke-RestMethod:SkipCertificateCheck", $true)
}
if ($PSEdition -EQ 'Desktop') {
# Enable communication with self signed certs when using Windows Powershell
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
if (-Not ([System.Management.Automation.PSTypeName]'TrustAllCertificatePolicy').Type) {
Add-Type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertificatePolicy : ICertificatePolicy {
public TrustAllCertificatePolicy() {}
public bool CheckValidationResult(
ServicePoint sPoint, X509Certificate certificate,
WebRequest wRequest, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertificatePolicy
}
}
# End of "Enable self-signed certificates" section
##########################################################################
#Region Non Exported Functions ######
Function Get-Password {
param (
[string]$user,
[string]$password
)
if ([string]::IsNullOrEmpty($password)) {
$secureString = Read-Host -Prompt "Enter the password for $user" -AsSecureString
$password = ConvertFrom-SecureString $secureString -AsPlainText
}
return $password
}
#EndRegion Non Exported Functions ######
##########################################################################
Function Stop-CloudComponent {
<#
.SYNOPSIS
Shutdown node(s) in a vCenter Server inventory
.DESCRIPTION
The Stop-CloudComponent cmdlet shutdowns the given node(s) in a vCenter Server inventory
.EXAMPLE
Stop-CloudComponent -server sfo-m01-vc01.sfo.rainpole.io -user adminstrator@vsphere.local -pass VMw@re1! -timeout 20 -nodes "sfo-m01-en01", "sfo-m01-en02"
This example connects to a vCenter Server and shuts down the nodes sfo-m01-en01 and sfo-m01-en02
.EXAMPLE
Stop-CloudComponent -server sfo-m01-vc01.sfo.rainpole.io -user root -pass VMw@re1! -timeout 20 pattern "^vCLS.*"
This example connects to an ESXi Host and shuts down the nodes that match the pattern vCLS.*
.PARAMETER server
The FQDN of the vCenter Server.
.PARAMETER user
The username to authenticate to vCenter Server.
.PARAMETER pass
The password to authenticate to vCenter Server.
.PARAMETER timeout
The timeout in seconds to wait for the cloud component to reach the desired connection state.
.PARAMETER noWait
To shudown the cloud component and not wait for desired connection state change.
.PARAMETER nodes
The FQDNs of the list of cloud components to shutdown.
.PARAMETER pattern
The cloud components matching the pattern in the SDDC Manager inventory to be shutdown.
#>
Param (
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
[Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$timeout,
[Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$noWait,
[Parameter (ParameterSetName = 'Node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String[]]$nodes,
[Parameter (ParameterSetName = 'Pattern', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String[]]$pattern
)
$pass = Get-Password -User $user -Password $pass
Try {
Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Stop-CloudComponent cmdlet."
$checkServer = (Test-EndpointConnection -server $server -Port 443)
if ($checkServer) {
Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..."
if ($DefaultVIServers) {
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
}
Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null
if ($DefaultVIServer.Name -EQ $server) {
if ($PSCmdlet.ParameterSetName -EQ "Node") {
$nodes_string = $nodes -join "; "
Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server' and attempting to shut down nodes '$nodes_string'..."
if ($nodes.Count -ne 0) {
foreach ($node in $nodes) {
$count = 0
if (Get-VM | Where-Object { $_.Name -EQ $node }) {
$vmObject = Get-VMGuest -Server $server -VM $node -ErrorAction SilentlyContinue
if ($vmObject.State -EQ 'NotRunning') {
Write-PowerManagementLogMessage -Type INFO -Message "Node '$node' is already powered off."
Continue
}
Write-PowerManagementLogMessage -Type INFO -Message "Attempting to shut down node '$node'..."
if ($PsBoundParameters.ContainsKey("noWait")) {
Stop-VM -Server $server -VM $node -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
} else {
Stop-VMGuest -Server $server -VM $node -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
Write-PowerManagementLogMessage -Type INFO -Message "Waiting for node '$node' to shut down..."
$sleepTime = 5
While (($vmObject.State -ne 'NotRunning') -and ($count -le $timeout)) {
Start-Sleep -s $sleepTime
$count = $count + $sleepTime
$vmObject = Get-VMGuest -Server $server -VM $node -ErrorAction SilentlyContinue
}
if ($count -gt $timeout) {
Write-PowerManagementLogMessage -Type ERROR -Message "Node '$node' did not shut down within the expected timeout $timeout value."
} else {
Write-PowerManagementLogMessage -Type INFO -Message "Node '$node' has shut down successfully."
}
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Unable to find node '$node' in the inventory of server '$server'."
}
}
}
}
if ($PSCmdlet.ParameterSetName -EQ "Pattern") {
Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server' and attempting to shut down nodes with pattern '$pattern'..."
if ($pattern) {
$patternNodes = Get-VM -Server $server | Where-Object Name -Match $pattern | Select-Object Name, PowerState, VMHost | Where-Object VMHost -Match $server
} else {
$patternNodes = @()
}
if ($patternNodes.Name.Count -ne 0) {
foreach ($node in $patternNodes) {
$count = 0
$vmObject = Get-VMGuest -Server $server -VM $node.Name | Where-Object VmUid -Match $server
if ($vmObject.State -EQ 'NotRunning') {
Write-PowerManagementLogMessage -Type INFO -Message "Node '$($node.name)' is already powered off."
Continue
}
Write-PowerManagementLogMessage -Type INFO -Message "Attempting to shut down node '$($node.name)'..."
if ($PsBoundParameters.ContainsKey("noWait")) {
Stop-VM -Server $server -VM $node.Name -Confirm:$false | Out-Null
} else {
Get-VMGuest -Server $server -VM $node.Name | Where-Object VmUid -Match $server | Stop-VMGuest -Confirm:$false | Out-Null
$vmObject = Get-VMGuest -Server $server -VM $node.Name | Where-Object VmUid -Match $server
$sleepTime = 1
While (($vmObject.State -ne 'NotRunning') -and ($count -le $timeout)) {
Start-Sleep -s $sleepTime
$count = $count + $sleepTime
$vmObject = Get-VMGuest -VM $node.Name | Where-Object VmUid -Match $server
}
if ($count -gt $timeout) {
Write-PowerManagementLogMessage -Type ERROR -Message "Node '$($node.name)' did not shut down within the expected timeout $timeout value."
} else {
Write-PowerManagementLogMessage -Type INFO -Message "Node '$($node.name)' has shut down successfully."
}
}
}
} elseif ($pattern) {
Write-PowerManagementLogMessage -Type WARNING -Message "No nodes match pattern '$pattern' on host '$server'."
}
}
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again."
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again"
}
} Catch {
Debug-CatchWriterForPowerManagement -object $_
} Finally {
Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Stop-CloudComponent cmdlet."
}
}
Export-ModuleMember -Function Stop-CloudComponent
Function Start-CloudComponent {
<#
.SYNOPSIS
Startup node(s) in a vCenter Server inventory
.DESCRIPTION
The Start-CloudComponent cmdlet starts up the given node(s) in a vCenter Server inventory
.EXAMPLE
Start-CloudComponent -server sfo-m01-vc01.sfo.rainpole.io -user adminstrator@vsphere.local -pass VMw@re1! -timeout 20 -nodes "sfo-m01-en01", "sfo-m01-en02"
This example connects to a vCenter Server and starts up the nodes sfo-m01-en01 and sfo-m01-en02
.EXAMPLE
Start-CloudComponent -server sfo-m01-vc01.sfo.rainpole.io -user root -pass VMw@re1! -timeout 20 pattern "^vCLS.*"
This example connects to an ESXi Host and starts up the nodes that match the pattern vCLS.*
.PARAMETER server
The FQDN of the vCenter Server.
.PARAMETER user
The username to authenticate to vCenter Server.
.PARAMETER pass
The password to authenticate to vCenter Server.
.PARAMETER timeout
The timeout in seconds to wait for the cloud component to reach the desired connection state.
.PARAMETER nodes
The FQDNs of the list of cloud components to startup.
.PARAMETER pattern
The cloud components matching the pattern in the SDDC Manager inventory to be startup.
#>
Param (
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
[Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [Int]$timeout,
[Parameter (ParameterSetName = 'Node', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String[]]$nodes,
[Parameter (ParameterSetName = 'Pattern', Mandatory = $true)] [ValidateNotNullOrEmpty()] [String[]]$pattern
)
$pass = Get-Password -User $user -Password $pass
Try {
Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Start-CloudComponent cmdlet."
$checkServer = (Test-EndpointConnection -server $server -Port 443)
if ($checkServer) {
Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..."
if ($DefaultVIServers) {
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
}
Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null
if ($DefaultVIServer.Name -EQ $server) {
if ($PSCmdlet.ParameterSetName -EQ "Node") {
$nodes_string = $nodes -join "; "
Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server' and attempting to start nodes '$nodes_string'."
if ($nodes.Count -ne 0) {
foreach ($node in $nodes) {
$count = 0
if (Get-VM | Where-Object { $_.Name -EQ $node }) {
$vmObject = Get-VMGuest -Server $server -VM $node -ErrorAction SilentlyContinue
if ($vmObject.State -EQ 'Running') {
Write-PowerManagementLogMessage -Type INFO -Message "Node '$node' is already in powered on."
Continue
}
Write-PowerManagementLogMessage -Type INFO -Message "Attempting to start up node '$node'..."
Start-VM -VM $node -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
Start-Sleep -s 5
$sleepTime = 10
Write-PowerManagementLogMessage -Type INFO -Message "Waiting for node '$node' to start up..."
While (($vmObject.State -ne 'Running') -and ($count -le $timeout)) {
Start-Sleep -s $sleepTime
$count = $count + $sleepTime
$vmObject = Get-VMGuest -Server $server -VM $node -ErrorAction SilentlyContinue
}
if ($count -gt $timeout) {
Write-PowerManagementLogMessage -Type ERROR -Message "Node '$node' did not start up within the expected timeout $timeout value."
Break
} else {
Write-PowerManagementLogMessage -Type INFO -Message "Node '$node' has started successfully."
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Cannot find '$node' in the inventory of host '$server'."
}
}
}
}
if ($PSCmdlet.ParameterSetName -EQ "Pattern") {
Write-PowerManagementLogMessage -Type INFO -Message "Connected to host '$server' and attempting to start up nodes with pattern '$pattern'..."
if ($pattern) {
$patternNodes = Get-VM -Server $server | Where-Object Name -Match $pattern | Select-Object Name, PowerState, VMHost | Where-Object VMHost -Match $server
} else {
$patternNodes = @()
}
if ($patternNodes.Name.Count -ne 0) {
foreach ($node in $patternNodes) {
$count = 0
$vmObject = Get-VMGuest -server $server -VM $node.Name | Where-Object VmUid -Match $server
if ($vmObject.State -EQ 'Running') {
Write-PowerManagementLogMessage -Type INFO -Message "Node '$($node.name)' is already powered on."
Continue
}
Start-VM -VM $node.Name | Out-Null
$sleepTime = 1
$vmObject = Get-VMGuest -Server $server -VM $node.Name | Where-Object VmUid -Match $server
Write-PowerManagementLogMessage -Type INFO -Message "Attempting to start up node '$($node.name)'..."
While (($vmObject.State -ne 'Running') -AND ($count -le $timeout)) {
Start-Sleep -s $sleepTime
$count = $count + $sleepTime
$vmObject = Get-VMGuest -Server $server -VM $node.Name | Where-Object VmUid -Match $server
}
if ($count -gt $timeout) {
Write-PowerManagementLogMessage -Type ERROR -Message "Node '$($node.name)' did not start up within the expected timeout $timeout value."
} else {
Write-PowerManagementLogMessage -Type INFO -Message "Node '$($node.name)' has started successfully."
}
}
} elseif ($pattern) {
Write-PowerManagementLogMessage -Type WARNING -Message "No nodes match pattern '$pattern' on host '$server'."
}
}
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to host '$server'. Check your environment and try again."
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again"
}
} Catch {
Debug-CatchWriterForPowerManagement -object $_
} Finally {
Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Start-CloudComponent cmdlet."
}
}
Export-ModuleMember -Function Start-CloudComponent
Function Set-MaintenanceMode {
<#
.SYNOPSIS
Enable or disable maintenance mode on an ESXi host.
.DESCRIPTION
The Set-MaintenanceMode cmdlet enables or disables maintenance mode on an ESXi host.
.EXAMPLE
Set-MaintenanceMode -server sfo01-w01-esx01.sfo.rainpole.io -user root -pass VMw@re1! -state ENABLE
This example places an ESXi host in maintenance mode.
.EXAMPLE
Set-MaintenanceMode -server sfo01-w01-esx01.sfo.rainpole.io -user root -pass VMw@re1! -state DISABLE
This example takes an ESXi host out of maintenance mode.
.PARAMETER server
The FQDN of the ESXi host.
.PARAMETER user
The username to authenticate to ESXi host.
.PARAMETER pass
The password to authenticate to ESXi host.
.PARAMETER state
The state of the maintenance mode to be set on ESXi host. Allowed states are "ENABLE" or "DISABLE".
#>
Param (
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
[Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass,
[Parameter (Mandatory = $true)] [ValidateSet("ENABLE", "DISABLE")] [String]$state
)
$pass = Get-Password -User $user -Password $pass
Try {
Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Set-MaintenanceMode cmdlet."
$checkServer = (Test-EndpointConnection -server $server -Port 443)
if ($checkServer) {
Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..."
if ($DefaultVIServers) {
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
}
Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null
if ($DefaultVIServer.Name -EQ $server) {
Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server' and attempting to $state maintenance mode..."
$hostStatus = (Get-VMHost -Server $server)
if ($state -EQ "ENABLE") {
if ($hostStatus.ConnectionState -EQ "Connected") {
Write-PowerManagementLogMessage -Type INFO -Message "Attempting to enter maintenance mode for '$server'..."
Get-View -Server $server -ViewType HostSystem -Filter @{"Name" = $server } | Where-Object { !$_.Runtime.InMaintenanceMode } | ForEach-Object { $_.EnterMaintenanceMode(0, $false, (New-Object VMware.Vim.HostMaintenanceSpec -Property @{vsanMode = (New-Object VMware.Vim.VsanHostDecommissionMode -Property @{objectAction = [VMware.Vim.VsanHostDecommissionModeObjectAction]::NoAction }) })) } | Out-Null
$hostStatus = (Get-VMHost -Server $server)
if ($hostStatus.ConnectionState -EQ "Maintenance") {
Write-PowerManagementLogMessage -Type INFO -Message "Host '$server' has entered maintenance mode successfully."
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Host '$server' did not enter maintenance mode. Check your environment and try again."
}
} elseif ($hostStatus.ConnectionState -EQ "Maintenance") {
Write-PowerManagementLogMessage -Type INFO -Message "Host '$server' has already entered maintenance mode."
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Host '$server' is not currently connected."
}
}
elseif ($state -EQ "DISABLE") {
if ($hostStatus.ConnectionState -EQ "Maintenance") {
Write-PowerManagementLogMessage -Type INFO -Message "Attempting to exit maintenance mode for '$server'..."
$task = Set-VMHost -VMHost $server -State "Connected" -RunAsync -WarningAction SilentlyContinue -ErrorAction SilentlyContinue
Wait-Task $task | Out-Null
$hostStatus = (Get-VMHost -Server $server)
if ($hostStatus.ConnectionState -EQ "Connected") {
Write-PowerManagementLogMessage -Type INFO -Message "Host '$server' has exited maintenance mode successfully."
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "The host '$server' did not exit maintenance mode. Check your environment and try again."
}
} elseif ($hostStatus.ConnectionState -EQ "Connected") {
Write-PowerManagementLogMessage -Type INFO -Message "Host '$server' has already exited maintenance mode"
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Host '$server' is not currently connected."
}
}
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again."
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again"
}
} Catch {
Debug-CatchWriterForPowerManagement -object $_
} Finally {
Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Set-MaintenanceMode cmdlet."
}
}
Export-ModuleMember -Function Set-MaintenanceMode
Function Get-MaintenanceMode {
<#
.SYNOPSIS
Get maintenance mode status on an ESXi host.
.DESCRIPTION
The Get-MaintenanceMode cmdlet gets the maintenance mode status on an ESXi host.
.EXAMPLE
Get-MaintenanceMode -server sfo01-w01-esx01.sfo.rainpole.io -user root -pass VMw@re1!
This example returns the ESXi host maintenance mode status.
.PARAMETER server
The FQDN of the ESXi host.
.PARAMETER user
The username to authenticate to ESXi host.
.PARAMETER pass
The password to authenticate to ESXi host.
#>
Param (
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
[Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass
)
$pass = Get-Password -User $user -Password $pass
Try {
Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-MaintenanceMode cmdlet."
$checkServer = (Test-EndpointConnection -server $server -Port 443)
if ($checkServer) {
Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..."
if ($DefaultVIServers) {
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
}
Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null
if ($DefaultVIServer.Name -EQ $server) {
$hostStatus = (Get-VMHost -Server $server)
Write-PowerManagementLogMessage -Type INFO -Message "Connected to server '$server'. The connection status is '$($hostStatus.ConnectionState)'."
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
return $hostStatus.ConnectionState
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again."
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again."
}
} Catch {
Debug-CatchWriterForPowerManagement -object $_
} Finally {
Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-MaintenanceMode cmdlet."
}
}
Export-ModuleMember -Function Get-MaintenanceMode
Function Set-DrsAutomationLevel {
<#
.SYNOPSIS
Set the DRS automation level
.DESCRIPTION
The Set-DrsAutomationLevel cmdlet sets the automation level of the cluster based on the setting provided
.EXAMPLE
Set-DrsAutomationLevel -server sfo-m01-vc01.sfo.rainpole.io -user administrator@vsphere.local -Pass VMw@re1! -cluster sfo-m01-cl01 -level PartiallyAutomated
Thi examples sets the DRS Automation level for the sfo-m01-cl01 cluster to Partially Automated
.PARAMETER server
The FQDN of the vCenter Server.
.PARAMETER user
The username to authenticate to vCenter Server.
.PARAMETER pass
The password to authenticate to vCenter Server.
.PARAMETER cluster
The name of the cluster on which the DRS automation level settings are to be applied.
.PARAMETER level
The DRS automation level to be set. The value can be one amongst ("FullyAutomated", "Manual", "PartiallyAutomated", "Disabled").
#>
Param (
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
[Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster,
[Parameter (Mandatory = $true)] [ValidateSet("FullyAutomated", "Manual", "PartiallyAutomated", "Disabled")] [String]$level
)
$pass = Get-Password -User $user -Password $pass
Try {
Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Set-DrsAutomationLevel cmdlet."
$checkServer = (Test-EndpointConnection -server $server -Port 443)
if ($checkServer) {
Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..."
if ($DefaultVIServers) {
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
}
Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null
if ($DefaultVIServer.Name -EQ $server) {
$drsStatus = Get-Cluster -Name $cluster -ErrorAction SilentlyContinue
if ($drsStatus) {
if ($drsStatus.DrsAutomationLevel -EQ $level) {
Write-PowerManagementLogMessage -Type INFO -Message "The vSphere DRS automation level for cluster '$cluster' is already '$level'."
} else {
$drsStatus = Set-Cluster -Cluster $cluster -DrsAutomationLevel $level -Confirm:$false
if ($drsStatus.DrsAutomationLevel -EQ $level) {
Write-PowerManagementLogMessage -Type INFO -Message "The vSphere DRS automation level for cluster '$cluster' has been set to '$level' successfully."
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Failed to set the vSphere DRS automation level for cluster '$cluster' to '$level'."
}
}
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Cluster '$cluster' not found on host '$server'. Check your environment and try again."
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again."
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again"
}
} Catch {
Debug-CatchWriterForPowerManagement -object $_
} Finally {
Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Set-DrsAutomationLevel cmdlet."
}
}
Export-ModuleMember -Function Set-DrsAutomationLevel
Function Set-VsanClusterPowerStatus {
<#
.SYNOPSIS
PowerOff or PowerOn the vSAN Cluster
.DESCRIPTION
The Set-VsanClusterPowerStatus cmdlet either powers off or powers on a vSAN cluster
.EXAMPLE
Set-VsanClusterPowerStatus -server sfo-m01-vc01.sfo.rainpole.io -user administrator@vsphere.local -Pass VMw@re1! -cluster sfo-m01-cl01 -PowerStatus clusterPoweredOff
This example powers off cluster sfo-m01-cl01
Set-VsanClusterPowerStatus -server sfo-m01-vc01.sfo.rainpole.io -user administrator@vsphere.local -Pass VMw@re1! -cluster sfo-m01-cl01 -PowerStatus clusterPoweredOn
This example powers on cluster sfo-m01-cl01
.PARAMETER server
The FQDN of the vCenter Server.
.PARAMETER user
The username to authenticate to vCenter Server.
.PARAMETER pass
The password to authenticate to vCenter Server.
.PARAMETER clustername
The name of the vSAN cluster on which the power settings are to be applied.
.PARAMETER mgmt
The switch used to ignore power settings if management domain information is passed.
.PARAMETER PowerStatus
The power state to be set for a given vSAN cluster. The value can be one amongst ("clusterPoweredOff", "clusterPoweredOn").
#>
Param (
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
[Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$clustername,
[Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [Switch]$mgmt,
[Parameter (Mandatory = $true)] [ValidateSet("clusterPoweredOff", "clusterPoweredOn")] [String]$PowerStatus
)
$pass = Get-Password -User $user -Password $pass
Try {
Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Set-VsanClusterPowerStatus cmdlet."
$checkServer = (Test-EndpointConnection -server $server -Port 443)
if ($checkServer) {
Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..."
if ($DefaultVIServers) {
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
}
Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null
if ($DefaultVIServer.Name -EQ $server) {
Import-Module VMware.VimAutomation.Storage
$vsanClient = [VMware.VimAutomation.Storage.Interop.V1.Service.StorageServiceFactory]::StorageCoreService.ClientManager.GetClientByConnectionId($DefaultVIServer.Id)
$vsanClusterPowerSystem = $vsanClient.VsanViewService.GetVsanViewById("VsanClusterPowerSystem-vsan-cluster-power-system")
# Populate the needed spec:
$spec = [VMware.Vsan.Views.PerformClusterPowerActionSpec]::new()
$spec.powerOffReason = "Shutdown through VMware Cloud Foundation script"
$spec.targetPowerStatus = $PowerStatus
$cluster = Get-Cluster $clustername
# TODO - Add check if there is task ID returned
$powerActionTask = $vsanClusterPowerSystem.PerformClusterPowerAction($cluster.ExtensionData.MoRef, $spec)
$task = Get-Task -Id $powerActionTask
$counter = 0
$sleepTime = 10 # in seconds
if (-Not $mgmt) {
do {
$task = Get-Task -Id $powerActionTask
if (-Not ($task.State -EQ "Error")) {
Write-PowerManagementLogMessage -Type INFO -Message "$PowerStatus task is $($task.PercentComplete)% completed."
}
Start-Sleep -s $sleepTime
$counter += $sleepTime
} while ($task.State -EQ "Running" -and ($counter -lt 1800))
if ($task.State -EQ "Error") {
if ($task.ExtensionData.Info.Error.Fault.FaultMessage -like "VMware.Vim.LocalizableMessage") {
Write-PowerManagementLogMessage -Type ERROR -Message "'$($PowerStatus)' task exited with a localized error message. Go to the vSphere Client for details and to take the necessary actions."
} else {
Write-PowerManagementLogMessage -Type WARN -Message "'$($PowerStatus)' task exited with the Message:$($task.ExtensionData.Info.Error.Fault.FaultMessage) and Error: $($task.ExtensionData.Info.Error)."
Write-PowerManagementLogMessage -Type ERROR -Message "Go to the vSphere Client for details and to take the necessary actions."
}
}
if ($task.State -EQ "Success") {
Write-PowerManagementLogMessage -Type INFO -Message "$PowerStatus task is completed successfully."
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "$PowerStatus task is blocked in $($task.State) state."
}
}
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again."
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again"
}
} Catch {
Debug-CatchWriterForPowerManagement -object $_
} Finally {
Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Set-VsanClusterPowerStatus cmdlet."
}
}
Export-ModuleMember -Function Set-VsanClusterPowerStatus
Function Invoke-VxrailClusterShutdown {
<#
.SYNOPSIS
Invoke the shut down command on a VxRail cluster.
.DESCRIPTION
The cmdlet will perform a dry run test prior to initiate a shutdown command on a VxRail cluster.
.EXAMPLE
Invoke-VxrailClusterShutdown -server sfo-w01-vxrm.sfo.rainpole.io -user administrator@vsphere.local -pass VMw@re1!
This example powers off a VxRail cluster cluster which is managed by the VxRail Manager sfo-w01-vxrm.sfo.rainpole.io controls.
#>
Param (
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$pass
)
Try {
Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Invoke-VxrailClusterShutdown cmdlet."
$checkServer = (Test-EndpointConnection -server $server -Port 443)
if ($checkServer) {
Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..."
if ($DefaultVIServers) {
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
}
# Prepare VxRail rest API headers and payload
$payloadTest = @{ dryrun = 'true' } | ConvertTo-Json
$payloadRun = @{ dryrun = 'false' } | ConvertTo-Json
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass))) # Create Basic Authentication Encoded Credentials
$headers = @{"Content-Type" = "application/json" }
$headers.Add("Authorization", "Basic $base64AuthInfo")
$uri = "https://$server/rest/vxm/v1/cluster/shutdown"
Write-PowerManagementLogMessage -Type INFO -Message "Starting VxRail cluster shutdown dry run."
$respond = Invoke-WebRequest -Method POST -Uri $uri -Headers $headers -Body $payloadTest -UseBasicParsing -SkipCertificateCheck
if ($respond.StatusCode -EQ "202" -or $respond.StatusCode -EQ "200") {
$requestID = $respond.content | ConvertFrom-Json
Write-PowerManagementLogMessage -Type INFO -Message "VxRail cluster shutdown request accepted(ID:$($requestID.request_id))"
$uri2 = "https://$server/rest/vxm/v1/requests/$($requestID.request_id)"
$loopCounter = 0
$loopCounterLimit = 13
while ($loopCounter -lt $loopCounterLimit) {
$respond2 = Invoke-WebRequest -Method GET -Uri $uri2 -Headers $headers -UseBasicParsing -SkipCertificateCheck
if ($respond2.StatusCode -EQ "202" -or $respond2.StatusCode -EQ "200") {
$checkProgress = $respond2.content | ConvertFrom-Json
if ($checkProgress.state -Match "COMPLETED" -or $checkProgress.state -Match "FAILED" ) {
break
}
}
Start-Sleep -s 10
$loopCounter += 1
}
if ($checkProgress.extension.passed -match "true") {
Write-PowerManagementLogMessage -Type INFO -Message "VxRail cluster shutdown dry run: SUCCEEDED."
Write-PowerManagementLogMessage -Type INFO -Message "Starting VxRail cluster shutdown."
$respond = Invoke-WebRequest -Method POST -Uri $uri -Headers $headers -Body $payloadRun -UseBasicParsing -SkipCertificateCheck
if ($respond.StatusCode -EQ "202" -or $respond.StatusCode -EQ "200") {
return $true
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "VxRail cluster shutdown: FAILED"
}
} else {
$errorMsg = ""
$checkProgress = $respond2.content | ConvertFrom-Json
$parsingError = $checkProgress.extension.status
foreach ($errorElement in $parsingError) {
if ($errorElement.checkResult -match "FAILED") {
$errorMsg = $errorMsg + "Label: $($errorElement.label),($($errorElement.checkResult)) `nMessage: $($errorElement.message)`n"
}
}
Write-PowerManagementLogMessage -Type ERROR -Message "VxRail cluster shutdown dry run: FAILED `n $errorMsg"
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "VxRail cluster shutdown: FAILED"
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again"
}
} Catch {
Debug-CatchWriterForPowerManagement -object $_
} Finally {
Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Invoke-VxrailClusterShutdown cmdlet."
}
}
Export-ModuleMember -Function Invoke-VxrailClusterShutdown
Function Get-poweronVMsOnRemoteDS {
<#
.SYNOPSIS
Get a list of VMs that reside on a vSAN HCI Mesh datastore hosted in a specified cluster
.DESCRIPTION
The Get-poweronVMsOnRemoteDS cmdlet returns a list of VMs that reside on a vSAN HCI Mesh datastore hosted in a specified cluster
.EXAMPLE
Get-poweronVMsOnRemoteDS -server sfo-m01-vc01.sfo.rainpole.io -user administrator@vsphere.local -Pass VMw@re1! -clustertocheck sfo-m01-cl01
This example returns the list of VMs that reside on a vSAN HCI Mesh datastore hosted in cluster sfo-m01-cl01.
.PARAMETER server
The FQDN of the vCenter Server.
.PARAMETER user
The username to authenticate to vCenter Server.
.PARAMETER pass
The password to authenticate to vCenter Server.
.PARAMETER clusterToCheck
The name of the remote cluster on which virtual machines are hosted.
#>
Param (
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
[Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$clusterToCheck
)
$pass = Get-Password -User $user -Password $pass
Try {
Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Get-poweronVMsOnRemoteDS cmdlet."
$checkServer = (Test-EndpointConnection -server $server -Port 443)
if ($checkServer) {
Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..."
if ($DefaultVIServers) {
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
}
Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null
if ($DefaultVIServer.Name -EQ $server) {
$TotalvSANDatastores = @()
$RemotevSANdatastores = @()
$TotalvSANDatastores = (Get-Cluster -Name $clusterToCheck | Get-Datastore | Where-Object { $_.Type -EQ "vSAN" }).Name
$RemotevSANdatastores = ((get-vsanClusterConfiguration -Cluster $clusterToCheck).RemoteDatastore).Name
$LocalvSANDatastores = $TotalvSANDatastores | Where-Object { $_ -notin $RemotevSANdatastores }
[Array]$PoweredOnVMs = @()
foreach ($localds in $LocalvSANDatastores) {
foreach ($cluster in (Get-Cluster).Name) {
if ($cluster -ne $clusterToCheck ) {
$MountedvSANdatastores = ((get-vsanClusterConfiguration -Cluster $cluster).RemoteDatastore).Name
foreach ($datastore in $MountedvSANdatastores) {
if ($datastore -EQ $localds) {
$datastoreID = Get-Datastore $datastore | ForEach-Object { $_.ExtensionData.MoRef }
$vms = (Get-Cluster -name $cluster | get-vm | Where-Object { $_.PowerState -EQ "PoweredOn" }) | Where-Object { $vm = $_; $datastoreID | Where-Object { $vm.DatastoreIdList -contains $_ } }
if ($vms) {
Write-PowerManagementLogMessage -Type INFO -Message "Remote VMs with names $vms are running on cluster '$cluster' and datastore '$datastore.' `n"
[Array]$PoweredOnVMs += $vms
}
}
}
}
}
}
return $PoweredOnVMs
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again."
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again"
}
} Catch {
Debug-CatchWriterForPowerManagement -object $_
} Finally {
Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Get-poweronVMsOnRemoteDS cmdlet."
}
}
Export-ModuleMember -Function Get-poweronVMsOnRemoteDS
Function Test-LockdownMode {
<#
.SYNOPSIS
Check if some of the ESXi hosts in the specified cluster is in lockdown mode.
.DESCRIPTION
The Test-LockdownMode cmdlet returns an error if an ESXi host in the cluster is in lockdown mode.
.EXAMPLE
Test-LockdownMode -server sfo-m01-vc01.sfo.rainpole.io -user administrator@vsphere.local -Pass VMw@re1! -cluster sfo-m01-cl01
This example checks if some of the ESXi hosts in the cluster sfo-m01-cl01 is in lockdown mode.
.PARAMETER server
The FQDN of the vCenter Server.
.PARAMETER user
The username to authenticate to vCenter Server.
.PARAMETER pass
The password to authenticate to vCenter Server.
.PARAMETER cluster
The name of the cluster to be checked for locked down ESXi hosts if any.
#>
Param (
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
[Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$cluster
)
$pass = Get-Password -User $user -Password $pass
Try {
Write-PowerManagementLogMessage -Type INFO -Message "Starting the call to the Test-LockdownMode cmdlet."
$checkServer = (Test-EndpointConnection -server $server -Port 443)
if ($checkServer) {
Write-PowerManagementLogMessage -Type INFO -Message "Connecting to '$server'..."
if ($DefaultVIServers) {
Disconnect-VIServer -Server * -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
}
Connect-VIServer -Server $server -Protocol https -User $user -Password $pass | Out-Null
if ($DefaultVIServer.Name -EQ $server) {
$hostsInCluster = @()
$hostsInCluster = Get-Cluster -Name $cluster | Get-VMHost
$hostsWithLockdown = ""
if ($hostsInCluster.count -ne 0) {
foreach ($esxiHost in $hostsInCluster) {
Write-PowerManagementLogMessage -Type INFO -Message "Checking lockdown mode for $esxiHost ...."
$lockdownStatus = (Get-VMHost -Name $esxiHost).ExtensionData.Config.LockdownMode
if ($lockdownStatus -EQ $null) {
$checkServer = (Test-EndpointConnection -server $esxiHost -Port 443)
if ($checkServer) {
Write-PowerManagementLogMessage -Type ERROR -Message "Cannot fetch information about lockdown mode for ESXi host $esxiHost!"
} else {
Write-PowerManagementLogMessage -Type WARNING -Message "Cannot fetch information about lockdown mode. Host $esxiHost is not reachable."
Write-PowerManagementLogMessage -Type ERROR -Message "Check the status on the ESXi host $esxiHost!"
}
} else {
if ($lockdownStatus -ne "lockdownDisabled") {
Write-PowerManagementLogMessage -Type WARNING -Message "Lockdown mode is enabled for ESXi host $esxiHost"
$hostsWithLockdown += ", $esxiHost"
}
}
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Cluster $cluster is not present on server $server. Check the input to the cmdlet."
}
if ([string]::IsNullOrEmpty($hostsWithLockdown)) {
Write-PowerManagementLogMessage -Type INFO -Message "Cluster $cluster does not have ESXi hosts in lockdown mode."
} else {
Write-PowerManagementLogMessage -Type INFO -Message "The following ESXi hosts are in lockdown mode: $hostsWithLockdown. Disable lockdown mode to continue."
Write-PowerManagementLogMessage -Type ERROR -Message "Some hosts are in lockdown mode. Disable lockdown mode to continue."
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Cannot connect to server '$server'. Check your environment and try again."
}
} else {
Write-PowerManagementLogMessage -Type ERROR -Message "Connection to '$server' has failed. Check your environment and try again."
}
} Catch {
Debug-CatchWriterForPowerManagement -object $_
} Finally {
Write-PowerManagementLogMessage -Type INFO -Message "Completed the call to the Test-LockdownMode cmdlet."
}
}
Export-ModuleMember -Function Test-LockdownMode
Function Get-VMRunningStatus {
<#
.SYNOPSIS
Gets the running state of a virtual machine
.DESCRIPTION
The Get-VMRunningStatus cmdlet gets the running status of the given nodes matching the pattern on an ESXi host
.EXAMPLE
Get-VMRunningStatus -server sfo-w01-esx01.sfo.rainpole.io -user root -pass VMw@re1! -pattern "^vCLS*"
This example connects to an ESXi host and searches for all virtual machines matching the pattern and gets their running status
.PARAMETER server
The FQDN of the ESXi host.
.PARAMETER user
The username to authenticate to ESXi host.
.PARAMETER pass
The password to authenticate to ESXi host.
.PARAMETER pattern
The pattern to match set of virtual machines.
.PARAMETER Status
The state of the virtual machine to be tested against. The value can be one amongst ("Running", "NotRunning"). The default value is "Running".
#>
Param (
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$server,
[Parameter (Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$user,
[Parameter (Mandatory = $false)] [ValidateNotNullOrEmpty()] [String]$pass,