-
Notifications
You must be signed in to change notification settings - Fork 5
/
VAMT.psm1
2565 lines (2282 loc) · 112 KB
/
VAMT.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
<#
.NOTES
===========================================================================
Created by: Austin Browder
Date: August 24, 2022
Organization: VMware Professional Services
===========================================================================
.EXAMPLE
Import-Module -Name .\VAMT.psm1
#>
#############################################################################################################################
#
#region Function Definitions
#
#############################################################################################################################
function Initialize-VIServer {
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String[]]$vCenters,
[Parameter()] #Optional if credentialDirectory is provided.
[PSCredential]$Credential,
[Parameter()] #Optional if Credential is provided.
[String]$credentialDirectory
)
if ($null -eq $Credential -and $null -eq $credentialDirectory) {
throw "Both Inputs 'Credential' and 'credentialDirectory' are empty. 1 OR Both are required for this function to work."
}
$connections = @()
foreach ($vCenter in $vCenters) {
try {
if ($null -eq $Credential) {
Write-Log -severityLevel Debug -logMessage "No credential for vCenter $vCenter was passed in via input parameter. Starting stored credential retrieval."
$cred = Get-StoredCredential -credName $vCenter -credentialDirectory $credentialDirectory
} elseif (![string]::IsNullOrEmpty($credentialDirectory)) {
Write-Log -severityLevel Debug -logMessage "Credential for vCenter $vCenter with Username $($cred.UserName) was passed in via input parameter. Overwriting stored credential."
$cred = Save-Credential -credName $vCenter -cred $Credential -credentialDirectory $credentialDirectory
} else {
$cred = $Credential
}
Write-Log -severityLevel Info -logMessage "Logging in to vCenter $vCenter with User: $($cred.UserName)"
$connection = Connect-VIServer $vCenter -Credential $cred -NotDefault -ErrorAction Stop
#extend the vIConnection to contain the credential used to connect it. This can be used later rather than retrieving the credential again if the session needs to be recreated (i.e. in a job)
$connection | Add-Member NoteProperty -Name Credential -Value $cred -Force
$connections += $connection
} catch {
Write-Log -severityLevel Error -logMessage "Failed to connect to $vCenter with the following Error:`n`t$($_.Exception.innerexception.message)"
Write-Log -severityLevel Warn -logMessage "In the case of expired/incorrect stored credentials, you can clear the credential file used to connect to vCenter located here: $credentialDirectory"
Write-Log -severityLevel Warn -logMessage "Cleaning up and exiting the execution."
try { Disconnect-VIServer * -Confirm:$false } catch {}
throw $_
}
}
return $connections
}
function Invoke-Move {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine[]]$vm,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl]$Server,
[parameter()]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Types.V1.Inventory.VIContainer]$Destination,
[parameter()]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Types.V1.Inventory.FolderContainer]$InventoryLocation,
[parameter()]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Types.V1.VirtualDevice.NetworkAdapter[]]$NetworkAdapter,
[parameter()]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Types.V1.AdvancedOption[]]$AdvancedOption,
[parameter()]
[ValidateNotNullOrEmpty()]
$Network,
[parameter()]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Types.V1.DatastoreManagement.StorageResource[]]$Datastore,
[Parameter()]
[Object]$logDefaults
)
if (!!$logDefaults) {
Write-Log -logDefaults $logDefaults -severityLevel Debug -logMessage "Starting 'Invoke-Move'."
}else {
Write-Log -severityLevel Debug -logMessage "Starting 'Invoke-Move'."
}
$moveParameters = @{
VM = $vm
Confirm = $false
Server = $Server
VMotionPriority = "High"
WhatIf = !!$WhatIf
ErrorAction = "Stop"
}
if ($null -ne $Destination) {
if ($Destination.ExtensionData.MoRef.Type -eq "ClusterComputeResource") {
$moveParameters.Destination = Get-VMHost -Location $compute | Where-Object {$_.ConnectionState -eq "Connected"} | Get-Random
} elseif ($Destination.ExtensionData.MoRef.Type -eq "ResourcePool") {
$tgtCluster = Get-Cluster -Id $compute.ExtensionData.Owner.ToString() -Server $tgtViConn
$moveParameters.Destination = Get-VMHost -Location $tgtCluster | Where-Object {$_.ConnectionState -eq "Connected"} | Get-Random
} else {
$moveParameters.Destination = $Destination
}
}
if ($null -ne $InventoryLocation) {
$moveParameters.InventoryLocation = $InventoryLocation
}
if ($null -ne $NetworkAdapter) {
$moveParameters.NetworkAdapter = $NetworkAdapter
}
if ($null -ne $AdvancedOption) {
$moveParameters.AdvancedOption = $AdvancedOption
}
#Check if we can use the Move-VM commandlet and use it if possible. Otherwise we'll have to use the relocation spec.
$netCheck = $Network | Where-Object {$null -ne $_.NetworkType}
if ($Datastore.Count -le 1 -and $netCheck.Count -in @(0,$Network.Count)) {
Write-Log -severityLevel Debug -logMessage "Using 'Move-VM' commandlet to perform migration."
if ($null -ne $Datastore) {
$moveParameters.Datastore = $Datastore[0]
}
if ($null -ne $Network) {
if ($null -ne $Network.NetworkType) {
$moveParameters.Network = $Network
} else {
$moveParameters.PortGroup = $Network
}
}
$vm = Move-VM @moveParameters
return $vm
}
#We must use relocate spec due to multiple target datastores OR multiple target Network types
if ($null -ne $Datastore) {
$moveParameters.Datastore = $Datastore
}
if ($null -ne $Network) {
$moveParameters.Network = $Network
}
Write-Log -severityLevel Debug -logMessage "Using 'RelocateVM' to perform migration."
$spec = New-Object VMware.Vim.VirtualMachineRelocateSpec
foreach ($key in $moveParameters.Keys) {
$value = $moveParameters[$key]
Write-Log -severityLevel Debug -logMessage "Processing key '$key' for the relocation spec with the value(s) '$value'"
if ($key -eq "Datastore") {
$vmDisks = $vm | Get-HardDisk | Sort-Object -Property Name #Sort 'Hard Disk 1', '...2', '...3', etc
$storagePodDSTable = @{}
#Keep VMX details at same location as Hard Disk 1
$spec.Datastore = New-Object VMware.Vim.ManagedObjectReference
if ($value[0].ExtensionData.MoRef.Type -eq "StoragePod") {
#This is a DatastoreCluster so we must choose a DS. Picking the one with the most space.
$ds = $value[0] | Get-Datastore | Sort-Object -Property FreeSpaceGB -Descending | Select-Object -First 1
$spec.Datastore = $ds.ExtensionData.MoRef
$storagePodDSTable.Add($value[0].Name,$ds)
} else {
$spec.Datastore = $value[0].ExtensionData.MoRef
}
#check how many target Datastores were passed. If 1, put everything on it.
if ($value.Count -eq 1) {
$dsIndex = 0
$singleDS = $true
} else {
$singleDS = $false
}
$spec.Disk = New-Object VMware.Vim.VirtualMachineRelocateSpecDiskLocator[]($vmDisks.Count)
for ($i = 0; $i -lt $vmDisks.Count; $i++) {
if (!$singleDS) {
$dsIndex = $i
}
$spec.Disk[$i] = New-Object VMware.Vim.VirtualMachineRelocateSpecDiskLocator
$spec.Disk[$i].DiskId = $vmDisks[$i].ExtensionData.Key
$spec.Disk[$i].Datastore = New-Object VMware.Vim.ManagedObjectReference
if ($value[$dsIndex].ExtensionData.MoRef.Type -eq "StoragePod") {
if ($null -ne $storagePodDSTable[$value[$dsIndex].Name]) {
$spec.Disk[$i].Datastore = $storagePodDSTable[$value[$dsIndex].Name].ExtensionData.MoRef
} else {
#This is a DatastoreCluster so we must choose a DS. Picking the one with the most space.
$ds = $value[$dsIndex] | Get-Datastore | Sort-Object -Property FreeSpaceGB -Descending | Select-Object -First 1
$spec.Disk[$i].Datastore = $ds.ExtensionData.MoRef
$storagePodDSTable.Add($value[$dsIndex].Name,$ds)
}
} else {
$spec.Disk[$i].Datastore = $value[$dsIndex].ExtensionData.MoRef
}
}
}
if ($key -eq "Network") {
$vmNetAdapters = $moveParameters["NetworkAdapter"]
if ($null -eq $vmNetAdapters) {
$vmNetAdapters = Get-NetworkAdapter -VM $vm | Sort-Object -Property Name
}
#check how many target Networks were passed. If 1, put everything on it.
if ($value.Count -eq 1) {
$netIndex = 0
$singleNet = $true
} else {
$singleNet = $false
}
$spec.DeviceChange = New-Object VMware.Vim.VirtualDeviceConfigSpec[] ($vmNetAdapters.Count)
for ($i = 0; $i -lt $vmNetAdapters.Count; $i++) {
if (!$singleNet) {
$netIndex = $i
}
$spec.DeviceChange[$i] = New-Object VMware.Vim.VirtualDeviceConfigSpec
#$spec.DeviceChange[$i].Device = $vmNetAdapters[$i].ExtensionData
$spec.DeviceChange[$i].Device = New-Object $vmNetAdapters[$i].ExtensionData.GetType().FullName
$spec.DeviceChange[$i].Device.Key = $vmNetAdapters[$i].ExtensionData.Key
if ($value[$netIndex].ExtensionData.MoRef.Type -eq "OpaqueNetwork") {
$spec.DeviceChange[$i].Device.Backing = New-Object VMware.Vim.VirtualEthernetCardOpaqueNetworkBackingInfo
$spec.DeviceChange[$i].Device.Backing.OpaqueNetworkId = $value[$netIndex].OpaqueNetworkId
$spec.DeviceChange[$i].Device.Backing.OpaqueNetworkType = $value[$netIndex].OpaqueNetworkType
} elseif ($value[$netIndex].ExtensionData.MoRef.Type -eq "Network") {
$spec.DeviceChange[$i].Device.Backing = New-Object VMware.Vim.VirtualEthernetCardNetworkBackingInfo
$spec.DeviceChange[$i].Device.Backing.DeviceName = $value[$netIndex].Name
} elseif ($value[$netIndex].ExtensionData.MoRef.Type -eq "DistributedVirtualPortgroup") {
$spec.DeviceChange[$i].Device.Backing = New-Object VMware.Vim.VirtualEthernetCardDistributedVirtualPortBackingInfo
$spec.DeviceChange[$i].Device.Backing.Port = New-Object VMware.Vim.DistributedVirtualSwitchPortConnection
$spec.DeviceChange[$i].Device.Backing.Port.SwitchUuid = $value[$netIndex].VirtualSwitch.Key
$spec.DeviceChange[$i].Device.Backing.Port.PortgroupKey = $value[$netIndex].Key
} else {
throw "Encountered unknown network type '$($value[$netIndex].ExtensionData.MoRef.Type)' while building relocation spec. Associated network: $($value[$netIndex].Name)."
}
$spec.DeviceChange[$i].Operation = 'edit'
}
}
if ($key -eq "InventoryLocation") {
$spec.Folder = New-Object VMware.Vim.ManagedObjectReference
$spec.Folder = $value.ExtensionData.MoRef
}
if ($key -eq "Destination") {
$spec.Host = New-Object VMware.Vim.ManagedObjectReference
$spec.Host = $value.ExtensionData.MoRef
$spec.Pool = New-Object VMware.Vim.ManagedObjectReference
if ($Destination.ExtensionData.MoRef.Type -eq "ResourcePool") {
$spec.Pool = $Destination.ExtensionData.MoRef
} else {
#Since $value is a Host here, we look for it's default res pool first.
$pool = $value | Get-ResourcePool -Name "Resources" -Server $Server -ErrorAction SilentlyContinue
if ($null -eq $pool) {
#if default res pool wasnt found, then it's likely in a cluster, search the parent.
$pool = $value.Parent | Get-ResourcePool -Name "Resources" -Server $Server
}
$spec.Pool = $pool.ExtensionData.MoRef
}
}
}
if ($vm.ExtensionData.Client.ServiceUrl -ne $Server.ServiceUri.AbsoluteUri) {
#The relocation spec requires credentials for cross vc.
# Make sure the viconn was created with VAMT Initialize-VIServer
if ($null -ne $Server.Credential) {
$spec.Service = New-Object VMware.Vim.ServiceLocator
$spec.Service.Credential = New-Object VMware.Vim.ServiceLocatorNamePassword
$spec.Service.Credential.Username = $Server.Credential.UserName
$spec.Service.Credential.Password = $Server.Credential.GetNetworkCredential().Password
} else {
throw "Credential property inside the specified VI Connection was null. This function should only be used with VI Connections created by VAMT\Initialize-VIServer."
}
#$cert = Get-VIMachineCertificate -Server $Server -VCenterOnly | ?{ $_.Subject -eq $Server.ServiceUri.Host }
#$spec.Service.SslThumbprint = ($cert.Certificate.Thumbprint -split '(..)' -ne '') -join ":"
$spec.Service.SslThumbprint = Get-SSLThumbprint -URL $Server.ServiceUri.AbsoluteUri
$spec.Service.InstanceUuid = $Server.InstanceUuid
$spec.Service.Url = $Server.ServiceUri.AbsoluteUri
}
$printSpec = $spec | ConvertTo-Json -Depth 10 | ConvertFrom-Json
if (!!$spec.Service.Credential.Password) {
$printSpec.Service.Credential.Password = "***********"
}
Write-Log -severityLevel Debug -logMessage "Built the following relocation spec: $($printSpec | ConvertTo-Json -Depth 10)"
Write-Log -severityLevel Info -logMessage "Starting Move Now."
$vm.ExtensionData.RelocateVM($spec,'highPriority')
return (Get-VM -Name $vm.Name -Server $Server)
}
function Get-StoredCredential {
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$credName,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$credentialDirectory
)
$credFile = "$credentialDirectory\$credName-$($env:USERNAME).cred"
if (Test-Path -Path $credFile) {
$cred = Import-Clixml -Path $credFile
Write-Log -severityLevel Debug -logMessage "Found credential for '$credName'. User: $($cred.UserName)"
} else {
Write-Log -severityLevel Debug -logMessage "No stored credential found for '$credName'."
$cred = Save-Credential -credName $credName -credentialDirectory $credentialDirectory
}
return $cred
}
function Save-Credential {
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$credName,
[Parameter()]
[PSCredential]$cred,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$credentialDirectory
)
$credFile = "$credentialDirectory\$credName-$($env:USERNAME).cred"
Write-Log -severityLevel Debug -logMessage "Preparing to set credential for '$credName'."
if ($null -eq $cred) {
$cred = Get-Credential -Message "Please enter the credentials to use for connections to '$credName'. Recommended Username format: user@domain"
}
$cred | Export-Clixml -Path $credFile
Write-Log -severityLevel Info -logMessage "Saved new credential for '$credName'. User: '$($cred.UserName)'"
return $cred
}
function Write-Log {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$logMessage,
[Parameter()]
[ValidateSet('Info','Warn','Debug','Error')]
[string]$severityLevel = 'Info',
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$logDir,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$logFileNamePrefix,
[Parameter()]
[String]$syslogServer,
[Parameter()]
[Int]$syslogPort,
[Parameter()] <#@{
'Write-Log:logDir' = 'C:\logs'
'Write-Log:logFileNamePrefix' = 'Migrate'
}#>
[Object]$logDefaults,
[Parameter()]
[Switch]$skipConsole,
[Parameter()]
[Switch]$debugLogging
)
if($null -ne $logDefaults) {
$Script:PSDefaultParameterValues = $logDefaults
}
if(![string]::IsNullOrEmpty($logDir) -and !(Test-Path $logDir)){
Write-Host "Logging directory for current execution ($logDir) was not found. Creating directory now. - $(Get-Date)" -foregroundColor Cyan
New-Item -Path $logDir -ItemType Directory -Force | Out-Null
}
$logDate = Get-Date
$logStamp = "[$severityLevel] $logDate"
$stampedlogMessage = "$logStamp - $logMessage"
switch ($severityLevel) {
"Info" {
$foregroundColor = [System.ConsoleColor] 10 <#Green#>
$logToConsole = !$skipConsole
$syslogSeverity = 6
break
} "Warn" {
$foregroundColor = [System.ConsoleColor] 14 <#Yellow#>
$logToConsole = !$skipConsole
$syslogSeverity = 4
break
} "Debug" {
$foregroundColor = [System.ConsoleColor] 11 <#Cyan#>
$logToConsole = $debugLogging -and !$skipConsole
$syslogSeverity = 7
break
} "Error" {
$foregroundColor = [System.ConsoleColor] 12 <#Red#>
$logToConsole = !$skipConsole
$syslogSeverity = 3
break
}
}
if ($logToConsole) {
Write-Host $stampedlogMessage -foregroundColor $foregroundColor
}
if (![string]::IsNullOrEmpty($logDir) -and ![string]::IsNullOrEmpty($logFileNamePrefix)) {
Add-Content -Path "$logDir/$($logFileNamePrefix)_Script_Log.log" -value $stampedlogMessage
if ($severityLevel -eq "Error") {
Add-content -Path "$logDir/$($logFileNamePrefix)_Error_Log.log" -value $stampedlogMessage
}
}
if (![string]::IsNullOrEmpty($syslogServer)) {
$params = @{}
$params.syslogServer = $syslogServer
$params.syslogPort = $syslogPort
$params.severityLevel = $syslogSeverity
$params.syslogMessage = $logMessage
$params.logDate = $logDate
$params.logFileNamePrefix = $logFileNamePrefix
$params.logDir = $logDir
Send-Syslog @params
}
}
function Send-Syslog {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$syslogServer,
[Parameter()]
[Int]$syslogPort = 514,
[Parameter()]
[ValidateSet(3,4,6,7)]
[Int]$severityLevel = 6,
[Parameter()]
[Int]$facility = 16,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[DateTime]$logDate,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$syslogMessage,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$logFileNamePrefix,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$logDir
)
$logParameters = @{
syslogServer = ""
logFileNamePrefix = $logFileNamePrefix
logDir = $logDir
}
try {
$UDP_Client = New-Object System.Net.Sockets.UdpClient
$UDP_Client.Connect($syslogServer, $syslogPort)
$priority = ($facility * 8) + $severityLevel
$timestamp = $logDate | Get-Date -Format "yyyy:MM:dd:-HH:mm:ss zzz"
$formattedSyslogMessage = "<{0}>{1} {2} {3}" -f [String]$priority, $timestamp, $env:COMPUTERNAME, $syslogMessage
$asciiEncoding = [System.Text.Encoding]::ASCII
$byteSyslogMessage = $asciiEncoding.GetBytes($formattedSyslogMessage)
$result = $UDP_Client.Send($byteSyslogMessage, $byteSyslogMessage.Length)
if ($result -eq $byteSyslogMessage.Length) {
#This causes far too many unnecessary logs in the logfile. Absence of logs can be seen as success. Left code incase needed later.
#Write-Log @logParameters -severityLevel Debug -logMessage "Successfully sent Syslog message. Payload size: $($byteSyslogMessage.Length) bytes." -skipConsole
} else {
Write-Log @logParameters -severityLevel Error -logMessage "Failed to send Syslog message. Payload size: $($byteSyslogMessage.Length) bytes. Sent payload $result bytes."
}
} catch {
Write-Log @logParameters -severityLevel Error -logMessage "Failed to send Syslog message with following exception:`n$_"
}
}
function Confirm-InChangeWindow {
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[DateTime]$executeTime,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[DateTime]$startWindow,
[Parameter()]
$endWindow
)
if ($startWindow -le $executeTime) {
if (!!$endWindow) {
if ($executeTime -lt $endWindow) {
return $true
}
} else {
#no end window specified so we are safe to proceed
return $true
}
}
return $false
}
function New-ScheduledExecution {
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[DateTime]$startTime,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[Hashtable]$parameters,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$scriptPath,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$workingDirectory
)
Write-Log -severityLevel Info -logMessage "Validating we are running in an Administrator console."
#Scheduled tasks can only be created by an admin console so we must first check.
$currentId = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$currentPrincipal = New-Object System.Security.Principal.WindowsPrincipal($currentId)
$administratorRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator
if ($currentPrincipal.IsInRole($administratorRole)) {
$currentUserPassword = Read-Host -AsSecureString -Prompt "Please enter the password for '$($currentId.Name)' to be used for creating the scheduled task"
$currentUserCred = New-Object System.Management.Automation.PSCredential -ArgumentList $currentId.Name, $currentUserPassword
$parameterString = ($parameters.GetEnumerator() | ForEach-Object {
$key = $_.Key
$value = $_.Value
switch ($value.GetType().Name) {
"SwitchParameter" {
"-$($key)"
break
} "Boolean" {
"-$($key) `$$($value)"
break
} "String" {
"-$($key) '$($value)'"
break
} "String[]" {
"-$($key) @('$($value -join ', ')')"
break
} "PSCredential" {
if ($key -eq "secureMailCred") {
"-useMailCred"
}
break
} Default {
"-$($key) $($value)"
break
}
}
}) -join ' '
$pwshArg = "-Command `"& '$scriptPath' $parameterString`""
#Write-Host $pwshArg
$taskAction = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument $pwshArg -WorkingDirectory $workingDirectory
$startTrigger = New-ScheduledTaskTrigger -At $startTime -Once -RandomDelay (New-TimeSpan -Seconds 10)
$taskParameters = @{
Action = $taskAction
TaskName = "VAMT_Scheduled_Run_$($startTime | Get-Date -f "yyyyMMdd-HHmmss")"
Trigger = $startTrigger
RunLevel = "Highest"
User = $currentId.Name
Password = $currentUserCred.GetNetworkCredential().Password
}
$taskResult = Register-ScheduledTask @taskParameters
} else {
Write-Log -severityLevel Error -logMessage "Creating a Schedule Task using PowerShell requires an Administrator console. Please re-launch the console as Administrator and execute the script again."
}
}
function Get-VMFolderPath {
param (
[Parameter(Mandatory)]
$folder,
[Parameter()]
[switch]$showHidden
)
$path = @()
while ($folder) {
$parent = $folder.Parent
if ($null -ne $parent -and $null -eq $parent.Parent -and !$showHidden) {
$folder = $parent
} else {
$path += $folder.Name
$folder = $parent
}
}
[Array]::Reverse($path)
return ($path -join "/")
}
function Confirm-Tags {
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[Object]$tagDetails,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl[]]$viConnections
)
$missingCategories = @()
$categories = $viConnections | ForEach-Object {
$viConn = $_
try {
$category = Get-TagCategory -Name $tagDetails.tagCatName -Server $viConn -ErrorAction Stop
if ($category.Cardinality -ne 'Single') {
throw "Tag cardinality was detected as '$($category.Cardinality)'. Must be set to 'Single'."
}
$category | Add-Member -MemberType NoteProperty -Name 'vCenter' -Value $viConn
$category
} catch {
Write-Log -severityLevel Error -logMessage "Failed to validate tag category '$($tagDetails.tagCatName)' in vCenter '$($viConn.Name)'. Error:`n`t$($_.Exception.message)"
$missingCategories += "'$($tagDetails.tagCatName)' in vCenter '$($viConn.Name)'"
}
}
if ($missingCategories.Length -gt 0) {
$message = "Missing or invalid category detected: $($missingCategories -join ', ')"
Write-Log -severityLevel Error -logMessage $message
throw $message
}
$missingTags = @()
$categories | ForEach-Object {
$category = $_
try {
$tag = Get-Tag -Name $tagDetails.readyTagName -Category $category -Server $category.vCenter -ErrorAction Stop
} catch {
Write-Log -severityLevel Error -logMessage "Failed to find tag '$($tagDetails.readyTagName)' in category '$($category.Name)' in vCenter '$($category.vCenter.Name)'. Error:`n`t$($_.Exception.message)"
$missingTags += "'$($tagDetails.readyTagName)' in vCenter '$($category.vCenter.Name)'"
}
try {
$tag = Get-Tag -Name $tagDetails.inProgressTagName -Category $category -Server $category.vCenter -ErrorAction Stop
} catch {
Write-Log -severityLevel Error -logMessage "Failed to find tag '$($tagDetails.inProgressTagName)' in category '$($category.Name)' in vCenter '$($category.vCenter.Name)'. Error:`n`t$($_.Exception.message)"
$missingTags += "'$($tagDetails.inProgressTagName)' in vCenter '$($category.vCenter.Name)'"
}
try {
$tag = Get-Tag -Name $tagDetails.completeTagName -Category $category -Server $category.vCenter -ErrorAction Stop
} catch {
Write-Log -severityLevel Error -logMessage "Failed to find tag '$($tagDetails.completeTagName)' in category '$($category.Name)' in vCenter '$($category.vCenter.Name)'. Error:`n`t$($_.Exception.message)"
$missingTags += "'$($tagDetails.completeTagName)' in vCenter '$($category.vCenter.Name)'"
}
try {
$tag = Get-Tag -Name $tagDetails.completeWithErrorsTagName -Category $category -Server $category.vCenter -ErrorAction Stop
} catch {
Write-Log -severityLevel Error -logMessage "Failed to find tag '$($tagDetails.completeWithErrorsTagName)' in category '$($category.Name)' in vCenter '$($category.vCenter.Name)'. Error:`n`t$($_.Exception.message)"
$missingTags += "'$($tagDetails.completeWithErrorsTagName)' in vCenter '$($category.vCenter.Name)'"
}
try {
$tag = Get-Tag -Name $tagDetails.failedTagName -Category $category -Server $category.vCenter -ErrorAction Stop
} catch {
Write-Log -severityLevel Error -logMessage "Failed to find tag '$($tagDetails.failedTagName)' in category '$($category.Name)' in vCenter '$($category.vCenter.Name)'. Error:`n`t$($_.Exception.message)"
$missingTags += "'$($tagDetails.failedTagName)' in vCenter '$($category.vCenter.Name)'"
}
try {
$tag = Get-Tag -Name $tagDetails.rollbackTagName -Category $category -Server $category.vCenter -ErrorAction Stop
} catch {
Write-Log -severityLevel Error -logMessage "Failed to find tag '$($tagDetails.rollbackTagName)' in category '$($category.Name)' in vCenter '$($category.vCenter.Name)'. Error:`n`t$($_.Exception.message)"
$missingTags += "'$($tagDetails.rollbackTagName)' in vCenter '$($category.vCenter.Name)'"
}
try {
$tag = Get-Tag -Name $tagDetails.readyToRollbackTagName -Category $category -Server $category.vCenter -ErrorAction Stop
} catch {
Write-Log -severityLevel Error -logMessage "Failed to find tag '$($tagDetails.readyToRollbackTagName)' in category '$($category.Name)' in vCenter '$($category.vCenter.Name)'. Error:`n`t$($_.Exception.message)"
$missingTags += "'$($tagDetails.readyToRollbackTagName)' in vCenter '$($category.vCenter.Name)'"
}
}
if ($missingTags.Length -gt 0) {
$message = "Missing tags detected: $($missingTags -join ', ')"
Write-Log -severityLevel Error -logMessage $message
throw $message
}
Write-Log -severityLevel Info -logMessage "All tags and categories have been validated."
}
function Confirm-CustomAttribute {
param(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$attributeName,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl[]]$viConnections
)
$viConnections | ForEach-Object {
$viConn = $_
$attr = Get-CustomAttribute -Server $viConn -Name $attributeName -ErrorAction Ignore
if (!$attr) {
Write-Log -severityLevel Info -logMessage "Failed to find vm attribute '$attributeName' in vCenter '$($viConn.Name)'. Creating it now."
$null = New-CustomAttribute -Server $viConn -Name $attributeName -TargetType VirtualMachine
} else {
Write-Log -severityLevel Info -logMessage "Found vm attribute '$attributeName' in vCenter '$($viConn.Name)'. No action required."
}
}
}
function Get-VMStateBasedOnTag {
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine]$vm,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl[]]$viConn,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$stateTagsCatName,
[Parameter()]
[Switch]$ignoreTags
)
if (!!$ignoreTags) {
return "Unknown(Skipped)"
}
$vm = get-vm $vm -Server $viConn
$tagAssignment = Get-TagAssignment -Entity $vm -Category $stateTagsCatName -Server $viConn
if (!$tagAssignment) {
Write-Log -severityLevel Warn -logMessage "No state tag applied to VM $($vm.name)."
return "notag"
}
if ($tagAssignment.Tag.Length -gt 1) {
$message = "Detected $($tagAssignment.Tag.Length) state tags applied to VM $($vm.name). Should not be possible with Single cardinality."
Write-Log -severityLevel Warn -logMessage $message
throw $message
}
return $tagAssignment.Tag.Name
}
function Set-VMStateTag {
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine]$vm,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$tagName,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String]$stateTagsCatName,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl[]]$viConn,
[Parameter()]
[Switch]$ignoreTags
)
if (!!$ignoreTags) {
return "Unknown(Skipped)"
}
$logParameters = @{
skipConsole = $false
}
if (![String]::IsNullOrWhiteSpace($envLogPrefix)) {
$logParameters.logFileNamePrefix = $envLogPrefix
}
try {
Write-Log @logParameters -severityLevel Info -logMessage "Refreshing VM '$($vm.Name)' object"
$vm = get-vm $vm -Server $viConn
#Update viConn incase more than 1 was passed.
$viConn = $viConn | Where-Object {$_.Id -eq ($vm.Uid -Split 'VirtualMachine' | Select-Object -First 1)}
Write-Log @logParameters -severityLevel Info -logMessage "Preparing to set '$stateTagsCatName : $tagName' tag on '$($vm.Name)'"
$currentTagAssignment = Get-TagAssignment -Entity $vm -Category $stateTagsCatName -Server $viConn
if (!!$currentTagAssignment) {
Remove-TagAssignment -TagAssignment $currentTagAssignment -Confirm:$false -WhatIf:(!!$WhatIf)
}
$tag = Get-Tag -Name $tagName -Category $stateTagsCatName -Server $viConn
$null = New-TagAssignment -Entity $vm -Tag $tag -Server $viConn -WhatIf:(!!$WhatIf)
Write-Log @logParameters -severityLevel Info -logMessage "Successfully to set '$stateTagsCatName : $tagName' tag on '$($vm.Name)'"
} catch {
Write-Log @logParameters -severityLevel Error -logMessage "Failed to set '$stateTagsCatName : $tagName' tag on '$($vm.Name)'"
throw $_
}
return $tag.Name
}
function Confirm-ActiveTasks {
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine]$vm,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl]$viConnection,
[Parameter()]
[Switch]$waitTasks
)
$logParameters = @{
skipConsole = $false
}
if (![String]::IsNullOrWhiteSpace($envLogPrefix)) {
$logParameters.logFileNamePrefix = $envLogPrefix
}
$activeTasks = Get-Task -Server $viConnection | Where-Object { $_.State -eq 'Running' -and $_.ObjectId -eq $vm.ExtensionData.MoRef.ToString() }
if(!!$activeTasks -and !!$waitTasks) {
Write-Log @logParameters -severityLevel Info -logMessage "$($activeTasks.Count) active tasks found on '$($vm.Name)'. Waiting for tasks to complete."
if (!$WhatIf) {
$null = Wait-Task -Task $activeTasks
}
return
}
return $activeTasks
}
function Get-VIObjectByObject {
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
$refObject,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl]$Server
)
if ($refObject.count -gt 1) {
$obj = @()
foreach ($element in $refObject) {
$obj += Get-VIObjectByVIView -MORef $element.Id -Server $Server
}
} else {
$obj = Get-VIObjectByVIView -MORef $refObject.Id -Server $Server
}
return $obj
}
function Test-VMTools {
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine]$vm
)
$toolsStatus = $vm.ExtensionData.Guest.ToolsStatus
if ($toolsStatus -in @("toolsOk", "toolsOld")) {
Write-Log -severityLevel Debug -logMessage "VM Tools on '$($vm.Name)' has been validated with status '$toolsStatus'."
return $true
}
Write-Log -severityLevel Warn -logMessage "VM Tools on '$($vm.Name)' failed validation with status '$toolsStatus'."
return $false
}
function Get-SSLThumbprint {
param(
[Parameter(Mandatory)]
[String]$url
)
#Original Author: William Lam (https://gist.github.com/lamw/988e4599c0f88d9fc25c9f2af8b72c92)
if ($null -eq ([System.Management.Automation.PSTypeName]'IDontCarePolicy').Type) {
add-type '
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class IDontCarePolicy : ICertificatePolicy {
public IDontCarePolicy() {}
public bool CheckValidationResult(
ServicePoint sPoint, X509Certificate cert,
WebRequest wRequest, int certProb) {
return true;
}
}
'
}
[System.Net.ServicePointManager]::CertificatePolicy = new-object IDontCarePolicy
# Need to connect using simple GET operation for this to work
try {Invoke-RestMethod -Uri $url -Method Get | Out-Null} catch {}
try {
$endpoint_request = [System.Net.Webrequest]::Create("$url")
$ssl_thumbprint = $endpoint_request.ServicePoint.Certificate.GetCertHashString()
} catch {
if ($null -eq $ssl_thumbprint) {
throw "Unable to retrieve Cert/Thumbprint from url '$url'. See error:`n`t$_"
}
}
return $ssl_thumbprint -replace '(..(?!$))','$1:'
}
function Start-PreMigrationExtensibility {
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter()]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl[]]$viConnection,
[Parameter()]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine]$vm
)
return $true
}
function Start-PostMigrationExtensibility {
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter()]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl[]]$viConnection,
[Parameter()]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Types.V1.Inventory.VirtualMachine]$vm
)
return $true
}
function Confirm-NotNullOrEmpty {
param (
[Parameter(Mandatory)]
[String]$inString,
[Parameter()]
[ValidateNotNullOrEmpty()]
[String]$failMessage = "Input is null or empty."
)
if ([String]::IsNullOrEmpty($inString)) {
Write-Log -severityLevel Error -logMessage $failMessage
throw $failMessage
}
return $inString
}
function Confirm-VMs {
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[VMware.VimAutomation.ViCore.Impl.V1.VIServerImpl[]]$viConnection,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String[]]$vmNames
)
$missingVMs = @()
$vms = $vmNames | ForEach-Object {
$vmname = $_
try{
$vm = Get-VM -Name $vmname -Server $viConnection -ErrorAction Stop
} catch {
Write-Log -severityLevel Warn -logMessage "No VM was found with name '$vmname'."
$missingVMs += $vmname
}
if ($vm.count -ne 1) {
Write-Log -severityLevel Warn -logMessage "$($vm.count) VM(s) found with name '$vmname'."