-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Expand file tree
/
Copy pathNew-AzMigrateLocalServerReplication.ps1
More file actions
884 lines (776 loc) · 43.6 KB
/
New-AzMigrateLocalServerReplication.ps1
File metadata and controls
884 lines (776 loc) · 43.6 KB
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
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------
<#
.Synopsis
Starts replication for the specified server.
.Description
The New-AzMigrateLocalServerReplication cmdlet starts the replication for a particular discovered server in the Azure Migrate project.
.Link
https://learn.microsoft.com/powershell/module/az.migrate/new-azmigratelocalserverreplication
#>
function New-AzMigrateLocalServerReplication {
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PreviewMessageAttribute("This cmdlet is based on a preview API version and may experience breaking changes in future releases.")]
[OutputType([Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.IJobModel])]
[CmdletBinding(DefaultParameterSetName = 'ByIdDefaultUser', PositionalBinding = $false, SupportsShouldProcess, ConfirmImpact = 'Medium')]
param(
[Parameter(ParameterSetName = 'ByIdDefaultUser', Mandatory)]
[Parameter(ParameterSetName = 'ByIdPowerUser', Mandatory)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the machine ARM ID of the discovered server to be migrated.
${MachineId},
[Parameter(Mandatory)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the storage path ARM ID where the VMs will be stored.
${TargetStoragePathId},
[Parameter()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.Int32]
# Specifies the number of CPU cores.
${TargetVMCPUCore},
[Parameter(ParameterSetName = 'ByIdDefaultUser', Mandatory)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the logical network ARM ID that the VMs will use.
${TargetVirtualSwitchId},
[Parameter(ParameterSetName = 'ByIdDefaultUser')]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the test logical network ARM ID that the VMs will use.
${TargetTestVirtualSwitchId},
[Parameter()]
[ValidateSet("true" , "false")]
[ArgumentCompleter( { "true" , "false" })]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies if RAM is dynamic or not.
${IsDynamicMemoryEnabled},
[Parameter()]
[ValidateSet("true" , "false")]
[ArgumentCompleter( { "true" , "false" })]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies whether the VM should be migrated as an Arc VM.
${MigrateAsArcVM},
[Parameter()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.Int64]
# Specifies the target RAM size in MB.
${TargetVMRam},
[Parameter(ParameterSetName = 'ByIdPowerUser', Mandatory)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.AzLocalDiskInput[]]
# Specifies the disks on the source server to be included for replication.
${DiskToInclude},
[Parameter(ParameterSetName = 'ByIdPowerUser', Mandatory)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.AzLocalNicInput[]]
# Specifies the NICs on the source server to be included for replication.
${NicToInclude},
[Parameter(Mandatory)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the target resource group ARM ID where the migrated VM resources will reside.
${TargetResourceGroupId},
[Parameter(Mandatory)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the name of the VM to be created.
${TargetVMName},
[Parameter(ParameterSetName = 'ByIdDefaultUser', Mandatory)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the operating system disk for the source server to be migrated.
${OSDiskID},
[Parameter(Mandatory)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the source appliance name for the AzLocal scenario.
${SourceApplianceName},
[Parameter(Mandatory)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[System.String]
# Specifies the target appliance name for the AzLocal scenario.
${TargetApplianceName},
[Parameter()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Path')]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.DefaultInfo(Script = '(Get-AzContext).Subscription.Id')]
[System.String]
# Azure Subscription ID.
${SubscriptionId},
[Parameter()]
[Alias('AzureRMContext', 'AzureCredential')]
[ValidateNotNull()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Azure')]
[System.Management.Automation.PSObject]
# The credentials, account, tenant, and subscription used for communication with Azure.
${DefaultProfile},
[Parameter(DontShow)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[System.Management.Automation.SwitchParameter]
# Wait for .NET debugger to attach
${Break},
[Parameter(DontShow)]
[ValidateNotNull()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SendAsyncStep[]]
# SendAsync Pipeline Steps to be appended to the front of the pipeline
${HttpPipelineAppend},
[Parameter(DontShow)]
[ValidateNotNull()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SendAsyncStep[]]
# SendAsync Pipeline Steps to be prepended to the front of the pipeline
${HttpPipelinePrepend},
[Parameter(DontShow)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[System.Uri]
# The URI for the proxy server to use
${Proxy},
[Parameter(DontShow)]
[ValidateNotNull()]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[System.Management.Automation.PSCredential]
# Credentials for a proxy server to use for the remote call
${ProxyCredential},
[Parameter(DontShow)]
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Category('Runtime')]
[System.Management.Automation.SwitchParameter]
# Use the default credentials for the proxy
${ProxyUseDefaultCredentials}
)
process {
$helperPath = [System.IO.Path]::Combine($PSScriptRoot, "Helper", "AzLocalCommonSettings.ps1")
Import-Module $helperPath
$helperPath = [System.IO.Path]::Combine($PSScriptRoot, "Helper", "AzLocalCommonHelper.ps1")
Import-Module $helperPath
CheckResourceGraphModuleDependency
CheckResourcesModuleDependency
$HasMachineId = $PSBoundParameters.ContainsKey('MachineId')
$HasTargetStoragePathId = $PSBoundParameters.ContainsKey('TargetStoragePathId')
$HasTargetResourceGroupId = $PSBoundParameters.ContainsKey('TargetResourceGroupId')
$HasTargetVMCPUCore = $PSBoundParameters.ContainsKey('TargetVMCPUCore')
$HasIsDynamicMemoryEnabled = $PSBoundParameters.ContainsKey('IsDynamicMemoryEnabled')
if ($HasIsDynamicMemoryEnabled) {
$isDynamicRamEnabled = [System.Convert]::ToBoolean($IsDynamicMemoryEnabled)
}
$HasMigrateAsArcVM = $PSBoundParameters.ContainsKey('MigrateAsArcVM')
if ($HasMigrateAsArcVM) {
$migrateAsArcVMEnabled = [System.Convert]::ToBoolean($MigrateAsArcVM)
}
$HasTargetVMRam = $PSBoundParameters.ContainsKey('TargetVMRam')
$HasTargetVirtualSwitchId = $PSBoundParameters.ContainsKey('TargetVirtualSwitchId')
$HasTargetTestVirtualSwitchId = $PSBoundParameters.ContainsKey('TargetTestVirtualSwitchId')
$parameterSet = $PSCmdlet.ParameterSetName
# Remove initial command parameters
$null = $PSBoundParameters.Remove('MachineId')
$null = $PSBoundParameters.Remove('TargetStoragePathId')
$null = $PSBoundParameters.Remove('TargetVMCPUCore')
$null = $PSBoundParameters.Remove('TargetVirtualSwitchId')
$null = $PSBoundParameters.Remove('TargetTestVirtualSwitchId')
$null = $PSBoundParameters.Remove('IsDynamicMemoryEnabled')
$null = $PSBoundParameters.Remove('MigrateAsArcVM')
$null = $PSBoundParameters.Remove('TargetVMRam')
$null = $PSBoundParameters.Remove('DiskToInclude')
$null = $PSBoundParameters.Remove('NicToInclude')
$null = $PSBoundParameters.Remove('TargetResourceGroupId')
$null = $PSBoundParameters.Remove('TargetVMName')
$null = $PSBoundParameters.Remove('OSDiskID')
$null = $PSBoundParameters.Remove('SourceApplianceName')
$null = $PSBoundParameters.Remove('TargetApplianceName')
# Set common ErrorVariable and ErrorAction for get behaviors
$null = $PSBoundParameters.Add('ErrorVariable', 'notPresent')
$null = $PSBoundParameters.Add('ErrorAction', 'SilentlyContinue')
# Validate ARM ID format from inputs
if ($HasMachineId -and !(Test-AzureResourceIdFormat -Data $MachineId -Format $IdFormats.MachineArmIdTemplate))
{
throw New-InvalidResourceIdProvidedException `
-ResourceId $MachineId `
-ResourceType "DiscoveredMachine" `
-Format $IdFormats.MachineArmIdTemplate
}
if ($HasTargetStoragePathId -and !(Test-AzureResourceIdFormat -Data $TargetStoragePathId -Format $IdFormats.StoragePathArmIdTemplate)) {
throw New-InvalidResourceIdProvidedException `
-ResourceId $TargetStoragePathId `
-ResourceType "StorageContainer" `
-Format $IdFormats.StoragePathArmIdTemplate
}
if ($HasTargetResourceGroupId -and !(Test-AzureResourceIdFormat -Data $TargetResourceGroupId -Format $IdFormats.ResourceGroupArmIdTemplate)) {
throw New-InvalidResourceIdProvidedException `
-ResourceId $TargetResourceGroupId `
-ResourceType "ResourceGroup" `
-Format $IdFormats.ResourceGroupArmIdTemplate
}
if ($HasTargetVirtualSwitchId -and !(Test-AzureResourceIdFormat -Data $TargetVirtualSwitchId -Format $IdFormats.LogicalNetworkArmIdTemplate)) {
throw New-InvalidResourceIdProvidedException `
-ResourceId $TargetVirtualSwitchId `
-ResourceType "LogicalNetwork" `
-Format $IdFormats.LogicalNetworkArmIdTemplate
}
if ($HasTargetTestVirtualSwitchId -and !(Test-AzureResourceIdFormat -Data $TargetTestVirtualSwitchId -Format $IdFormats.LogicalNetworkArmIdTemplate)) {
throw New-InvalidResourceIdProvidedException `
-ResourceId $TargetTestVirtualSwitchId `
-ResourceType "LogicalNetwork" `
-Format $IdFormats.LogicalNetworkArmIdTemplate
}
# $MachineId is in the format of
# "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.OffAzure/{2}/{3}/machines/{4}"
$MachineIdArray = $MachineId.Split("/")
$ResourceGroupName = $MachineIdArray[4] # {1}
$SiteType = $MachineIdArray[7] # {2}
$SiteName = $MachineIdArray[8] # {3}
$MachineName = $MachineIdArray[10] # {4}
# Get the source site and the discovered machine
if ($SiteType -eq $SiteTypes.HyperVSites) {
$instanceType = $AzLocalInstanceTypes.HyperVToAzLocal
# Get Hyper-V site with ResourceGroupName, SiteName
$null = $PSBoundParameters.Add('ResourceGroupName', $ResourceGroupName)
$null = $PSBoundParameters.Add('SiteName', $SiteName)
$siteObject = Az.Migrate.Internal\Get-AzMigrateHyperVSite @PSBoundParameters
if ($null -eq $siteObject)
{
throw New-AzMigrateSiteNotFoundException `
-Name $SiteName `
-ResourceGroupName $ResourceGroupName `
-SiteType $SiteType
}
# Get Hyper-V machine with ResourceGroupName, SiteName, MachineName
$null = $PSBoundParameters.Add('MachineName', $MachineName)
$machine = Az.Migrate.Internal\Get-AzMigrateHyperVMachine @PSBoundParameters
if ($null -eq $machine)
{
throw New-AzMigrateDiscoveredMachineNotFoundException `
-Name $MachineName `
-ResourceGroupName $ResourceGroupName `
-SiteName $SiteName
}
$null = $PSBoundParameters.Remove('MachineName')
# Get RunAsAccount
if (![string]::IsNullOrEmpty($machine.HostId))
{
# machine is on a single Hyper-V host
$hostIdArray = $machine.HostId.Split("/")
if ($hostIdArray.Length -lt 11) {
throw "Invalid Hyper-V Host ARM ID '$($machine.HostId)'"
}
$hostResourceGroupName = $hostIdArray[4]
$hostSiteName = $hostIdArray[8]
$hostName = $hostIdArray[10]
# Get Hyper-V host with ResourceGroupName, SiteName, HostName
$null = $PSBoundParameters.Add('HostName', $hostName)
$hyperVHost = Az.Migrate.Internal\Get-AzMigrateHyperVHost @PSBoundParameters
if ($null -eq $hyperVHost)
{
throw New-OffAzureResourceNotFoundException `
-Scenario "HyperV" `
-Type "Host" `
-Name $hostName `
-ResourceGroupName $hostResourceGroupName `
-SiteName $hostSiteName
}
$null = $PSBoundParameters.Remove('HostName')
$runAsAccountId = $hyperVHost.RunAsAccountId
}
elseif(![string]::IsNullOrEmpty($machine.ClusterId))
{
# machine is on a Hyper-V cluster
$clusterIdArray = $machine.ClusterId.Split("/")
if ($clusterIdArray.Length -lt 11) {
throw "Invalid Hyper-V Cluster ARM ID '$($machine.ClusterId)'"
}
$clusterResourceGroupName = $clusterIdArray[4]
$clusterSiteName = $clusterIdArray[8]
$clusterName = $clusterIdArray[10]
# Get Hyper-V cluster with ResourceGroupName, SiteName, ClusterName
$null = $PSBoundParameters.Add('ClusterName', $clusterName)
$hyperVCluster = Az.Migrate.Internal\Get-AzMigrateHyperVCluster @PSBoundParameters
if ($null -eq $hyperVCluster)
{
throw throw New-OffAzureResourceNotFoundException `
-Scenario "HyperV" `
-Type "Cluster" `
-Name $clusterName `
-ResourceGroupName $clusterResourceGroupName `
-SiteName $clusterSiteName
}
$null = $PSBoundParameters.Remove('ClusterName')
$runAsAccountId = $hyperVCluster.RunAsAccountId
}
}
elseif ($SiteType -eq $SiteTypes.VMwareSites)
{
$instanceType = $AzLocalInstanceTypes.VMwareToAzLocal
# Get VMware site with ResourceGroupName, SiteName
$null = $PSBoundParameters.Add('ResourceGroupName', $ResourceGroupName)
$null = $PSBoundParameters.Add('SiteName', $SiteName)
$siteObject = Az.Migrate.private\Get-AzMigrateSite_Get @PSBoundParameters
if ($null -eq $siteObject)
{
throw New-AzMigrateSiteNotFoundException `
-Name $SiteName `
-ResourceGroupName $ResourceGroupName `
-SiteType $SiteType
}
# Get VMware machine with ResourceGroupName, SiteName, MachineName
$null = $PSBoundParameters.Add('MachineName', $MachineName)
$machine = Az.Migrate.Internal\Get-AzMigrateMachine @PSBoundParameters
if ($null -eq $machine)
{
throw New-AzMigrateDiscoveredMachineNotFoundException `
-Name $MachineName `
-ResourceGroupName $ResourceGroupName `
-SiteName $SiteName
}
$null = $PSBoundParameters.Remove('MachineName')
# Get RunAsAccount
if (![string]::IsNullOrEmpty($machine.VCenterId))
{
# machine is on a single vCenter
$vCenterIdArray = $machine.VCenterId.Split("/")
if ($vCenterIdArray.Length -lt 11) {
throw "Invalid VMware vCenter ARM ID '$($machine.VCenterId)'"
}
$vCenterResourceGroupName = $vCenterIdArray[4]
$vCenterSiteName = $vCenterIdArray[8]
$vCenterName = $vCenterIdArray[10]
# Get VMware vCenter with ResourceGroupName, SiteName, Name
$null = $PSBoundParameters.Add('Name', $vCenterName)
$vmwareVCenter = Az.Migrate.Internal\Get-AzMigrateVCenter @PSBoundParameters
if ($null -eq $vmwareVCenter)
{
throw New-OffAzureResourceNotFoundException `
-Scenario "VMware" `
-Type "VCenter" `
-Name $vCenterName `
-ResourceGroupName $vCenterResourceGroupName `
-SiteName $vCenterSiteName
}
$null = $PSBoundParameters.Remove('Name')
$runAsAccountId = $vmwareVCenter.RunAsAccountId
}
}
else
{
throw "Site type of '$SiteType' in -MachineId is not supported. Only '$($SiteTypes.HyperVSites)' and '$($SiteTypes.VMwareSites)' are supported."
}
if ([string]::IsNullOrEmpty($runAsAccountId)) {
throw "Unable to determine RunAsAccount for site '$SiteName' from machine '$MachineName'. Please verify your appliance setup and provided -MachineId."
}
$null = $PSBoundParameters.Remove('SiteName')
# $siteObject is not null or exception would have been thrown
$ProjectName = $siteObject.DiscoverySolutionId.Split("/")[8]
# Get Data Replication Service (AMH solution) with ResourceGroupName, Name, MigrateProjectName
$amhSolutionName = $AzMigrateSolutions.DataReplicationSolution
$null = $PSBoundParameters.Add('MigrateProjectName', $ProjectName)
$null = $PSBoundParameters.Add('Name', $amhSolutionName)
$amhSolution = Az.Migrate.private\Get-AzMigrateSolution_Get @PSBoundParameters
if ($null -eq $amhSolution)
{
throw New-AzMigrateSolutionNotFoundException `
-Name $amhSolutionName `
-ResourceGroupName $ResourceGroupName `
-ProjectName $ProjectName
}
$null = $PSBoundParameters.Remove('Name')
$null = $PSBoundParameters.Remove('MigrateProjectName')
# Validate replication vault
$vaultId = $amhSolution.DetailExtendedDetail["vaultId"]
$vaultIdArray = $vaultId.Split("/")
if ($vaultIdArray.Length -lt 9)
{
throw New-ReplicationVaultNotFoundInAMHSolutionException -VaultId $vaultId
}
$replicationVaultName = $vaultIdArray[8]
# Get replication vault with ResourceGroupName, Name
$null = $PSBoundParameters.Add('Name', $replicationVaultName)
$replicationVault = Az.Migrate.Internal\Get-AzMigrateVault @PSBoundParameters
if ($null -eq $replicationVault)
{
throw "No Replication Vault '$replicationVaultName' found in Resource Group '$ResourceGroupName'. Please verify your Azure Migrate project setup."
}
elseif ($replicationVault.Property.ProvisioningState -ne [ProvisioningState]::Succeeded)
{
throw "The Replication Vault '$replicationVaultName' is not in a valid state. The provisioning state is '$($replicationVault.Property.ProvisioningState)'. Please verify your Azure Migrate project setup."
}
$null = $PSBoundParameters.Remove('Name')
# Validate replication prequisites
Test-ReplicationPrequisites `
-ResourceGroupName $ResourceGroupName `
-VaultName $replicationVaultName `
-ProtectedItemName $MachineName `
-MigrationType $instanceType
# Access Discovery Service
$discoverySolutionName = $AzMigrateSolutions.DiscoverySolution
# Get Discovery Solution with ResourceGroupName, Name, MigrateProjectName
$null = $PSBoundParameters.Add('Name', $discoverySolutionName)
$null = $PSBoundParameters.Add('MigrateProjectName', $ProjectName)
$discoverySolution = Az.Migrate.private\Get-AzMigrateSolution_Get @PSBoundParameters
if ($null -eq $discoverySolution)
{
throw New-AzMigrateSolutionNotFoundException `
-Name $discoverySolutionName `
-ResourceGroupName $ResourceGroupName `
-ProjectName $ProjectName
}
$null = $PSBoundParameters.Remove('MigrateProjectName')
$null = $PSBoundParameters.Remove('Name')
# Get Appliances Mapping
$appMap = @{}
if ($null -ne $discoverySolution.DetailExtendedDetail["applianceNameToSiteIdMapV2"]) {
$appMapV2 = $discoverySolution.DetailExtendedDetail["applianceNameToSiteIdMapV2"] | ConvertFrom-Json
# Fetch all appliance from V2 map first. Then these can be updated if found again in V3 map.
foreach ($item in $appMapV2) {
$appMap[$item.ApplianceName.ToLower()] = $item.SiteId
}
}
if ($null -ne $discoverySolution.DetailExtendedDetail["applianceNameToSiteIdMapV3"]) {
$appMapV3 = $discoverySolution.DetailExtendedDetail["applianceNameToSiteIdMapV3"] | ConvertFrom-Json
foreach ($item in $appMapV3) {
$t = $item.psobject.properties
$appMap[$t.Name.ToLower()] = $t.Value.SiteId
}
}
if ($null -eq $discoverySolution.DetailExtendedDetail["applianceNameToSiteIdMapV2"] -And
$null -eq $discoverySolution.DetailExtendedDetail["applianceNameToSiteIdMapV3"] ) {
throw "Server Discovery Solution missing Appliance Details. Invalid Solution."
}
$hyperVSiteTypeRegex = "(?<=/Microsoft.OffAzure/HyperVSites/).*$"
$vmwareSiteTypeRegex = "(?<=/Microsoft.OffAzure/VMwareSites/).*$"
# Validate SourceApplianceName & TargetApplianceName
$sourceSiteId = $appMap[$SourceApplianceName.ToLower()]
$targetSiteId = $appMap[$TargetApplianceName.ToLower()]
if (-not ($sourceSiteId -match $hyperVSiteTypeRegex -and $targetSiteId -match $hyperVSiteTypeRegex) -and
-not ($sourceSiteId -match $vmwareSiteTypeRegex -and $targetSiteId -match $hyperVSiteTypeRegex)) {
throw "Error encountered in matching the given source appliance name '$SourceApplianceName' and target appliance name '$TargetApplianceName'. Please verify the VM site type to be either for HyperV or VMware for both source and target appliances, and the appliance names are correct."
}
# Get healthy asrv2 fabrics in the resource group
# Get all fabrics with ResourceGroupName
$allFabrics = Az.Migrate.private\Get-AzMigrateLocalReplicationFabric_List1 @PSBoundParameters `
| Where-Object {
$_.Property.ProvisioningState -eq [ProvisioningState]::Succeeded -and
$_.Property.CustomProperty.MigrationSolutionId -eq $amhSolution.Id
}
# Filter for source fabric
if ($instanceType -eq $AzLocalInstanceTypes.HyperVToAzLocal)
{
$fabricInstanceType = $FabricInstanceTypes.HyperVInstance
}
else { # $instanceType -eq $AzLocalInstanceTypes.VMwareToAzLocal
$fabricInstanceType = $FabricInstanceTypes.VmwareInstance
}
$sourceFabric = $allFabrics | Where-Object {
$_.Property.CustomProperty.InstanceType -ceq $fabricInstanceType -and
$_.Name.StartsWith($SourceApplianceName, [System.StringComparison]::InvariantCultureIgnoreCase)
}
if ($null -eq $sourceFabric)
{
throw "Couldn't find connected source appliance with the name '$SourceApplianceName'. Deploy a source appliance by completing the Discover step of migration for your on-premises environment."
}
# Get source fabric agent (dra) with ResourceGroupName, FabricName
$null = $PSBoundParameters.Add('FabricName', $sourceFabric.Name)
$sourceDras = Az.Migrate.Internal\Get-AzMigrateFabricAgent @PSBoundParameters
$sourceDra = $sourceDras | Where-Object {
$_.Property.MachineName -eq $SourceApplianceName -and
$_.Property.CustomProperty.InstanceType -eq $fabricInstanceType -and
$_.Property.IsResponsive -eq $true
}
if ($null -eq $sourceDra)
{
throw "The source appliance '$SourceApplianceName' is in a disconnected state. Ensure that the source appliance is running and has connectivity before proceeding."
}
$null = $PSBoundParameters.Remove('FabricName')
$sourceDra = $sourceDra[0]
# Filter for target fabric
$fabricInstanceType = $FabricInstanceTypes.AzLocalInstance
$targetFabric = $allFabrics | Where-Object {
$_.Property.CustomProperty.InstanceType -ceq $fabricInstanceType -and
$_.Name.StartsWith($TargetApplianceName, [System.StringComparison]::InvariantCultureIgnoreCase)
}
if ($null -eq $targetFabric)
{
throw "Couldn't find connected target appliance with the name '$TargetApplianceName'. Deploy a target appliance by completing the Configuration step of migration for your Azure Local environment."
}
# Get target fabric agent (dra) with ResourceGroupName, FabricName
$null = $PSBoundParameters.Add('FabricName', $targetFabric.Name)
$targetDras = Az.Migrate.Internal\Get-AzMigrateFabricAgent @PSBoundParameters
$targetDra = $targetDras | Where-Object {
$_.Property.MachineName -eq $TargetApplianceName -and
$_.Property.CustomProperty.InstanceType -eq $fabricInstanceType -and
$_.Property.IsResponsive -eq $true
}
if ($null -eq $targetDra)
{
"The target appliance '$TargetApplianceName' is in a disconnected state. Ensure that the target appliance is running and has connectivity before proceeding."
}
$null = $PSBoundParameters.Remove('FabricName')
$targetDra = $targetDras[0]
# Validate Policy
$policyName = $replicationVaultName + $instanceType + "policy"
# Get replication policy with ResourceGroupName, Name, VaultName
$null = $PSBoundParameters.Add('Name', $policyName)
$null = $PSBoundParameters.Add('VaultName', $replicationVaultName)
$policy = Az.Migrate.Internal\Get-AzMigratePolicy @PSBoundParameters
if ($null -eq $policy)
{
throw "The replication policy '$policyName' not found. The replication infrastructure is not initialized. Run the Initialize-AzMigrateLocalReplicationInfrastructure command."
}
elseif ($policy.Property.ProvisioningState -ne [ProvisioningState]::Succeeded)
{
throw "The replication policy '$policyName' is not in a valid state. The provisioning state is '$($policy.Property.ProvisioningState)'. Re-run the Initialize-AzMigrateLocalReplicationInfrastructure command."
}
$null = $PSBoundParameters.Remove('Name')
# Validate Replication Extension
$replicationExtensionName = ($sourceFabric.Id -split '/')[-1] + "-" + ($targetFabric.Id -split '/')[-1] + "-MigReplicationExtn"
# Get replication extension with ResourceGroupName, Name, VaultName
$null = $PSBoundParameters.Add('Name', $replicationExtensionName)
$replicationExtension = Az.Migrate.Internal\Get-AzMigrateReplicationExtension @PSBoundParameters
if ($null -eq $replicationExtension)
{
throw "The replication extension '$replicationExtensionName' not found. The replication infrastructure is not initialized. Run the Initialize-AzMigrateLocalReplicationInfrastructure command."
}
elseif ($replicationExtension.Property.ProvisioningState -ne [ProvisioningState]::Succeeded)
{
throw "The replication extension '$replicationExtensionName' is not in a valid state. The provisioning state is '$($replicationExtension.Property.ProvisioningState)'. Re-run the Initialize-AzMigrateLocalReplicationInfrastructure command."
}
$null = $PSBoundParameters.Remove('Name')
# Get ARC Resource Bridge info
$targetClusterId = $targetFabric.Property.CustomProperty.Cluster.ResourceName
$targetClusterIdArray = $targetClusterId.Split("/")
$targetSubscription = $targetClusterIdArray[2]
$arbArgQuery = GetARGQueryForArcResourceBridge -HCIClusterID $targetClusterId
$arbArgResult = Az.ResourceGraph\Search-AzGraph -Query $arbArgQuery -Subscription $targetSubscription
if ($null -eq $arbArgResult) {
throw "$($ArcResourceBridgeValidationMessages.NoClusters). Validate target cluster with id '$targetClusterId' exists."
}
elseif ($arbArgResult.statusOfTheBridge -ne "Running") {
throw "$($ArcResourceBridgeValidationMessages.NotRunning). Make sure the Arc Resource Bridge is online before retrying."
}
# Validate TargetVMName
if ($TargetVMName.length -gt 64 -or $TargetVMName.length -eq 0) {
throw "The target virtual machine name must be between 1 and 64 characters long."
}
elseif ($TargetVMName -notmatch "^[^_\W][a-zA-Z0-9\-]{0,63}(?<![-._])$") {
throw "The target virtual machine name must begin with a letter or number, and can contain only letters, numbers, or hyphens(-). The names cannot contain special characters \/""[]:|<>+=;,?*@&, whitespace, or begin with '_' or end with '.' or '-'."
}
elseif (IsReservedOrTrademarked($TargetVMName)) {
throw "The target virtual machine name '$TargetVMName' or part of the name is a trademarked or reserved word."
}
# Construct create protected item request object
$protectedItemProperties = [Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.ProtectedItemModelProperties]::new()
$protectedItemProperties.PolicyName = $policyName
$protectedItemProperties.ReplicationExtensionName = $replicationExtensionName
if ($SiteType -eq $SiteTypes.HyperVSites) {
$customProperties = [Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.HyperVToAzStackHciprotectedItemModelCustomProperties]::new()
$isSourceDynamicMemoryEnabled = $machine.IsDynamicMemoryEnabled
}
elseif ($SiteType -eq $SiteTypes.VMwareSites) {
$customProperties = [Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.VMwareToAzStackHciprotectedItemModelCustomProperties]::new()
$isSourceDynamicMemoryEnabled = $false
}
$customProperties.InstanceType = $instanceType
$customProperties.CustomLocationRegion = $arbArgResult.CustomLocationRegion
$customProperties.FabricDiscoveryMachineId = $machine.Id
$customProperties.RunAsAccountId = $runAsAccountId
$customProperties.SourceFabricAgentName = $sourceDra.Name
$customProperties.StorageContainerId = $TargetStoragePathId
$customProperties.TargetArcClusterCustomLocationId = $arbArgResult.CustomLocation
$customProperties.TargetFabricAgentName = $targetDra.Name
$customProperties.TargetHciClusterId = $targetClusterId
$customProperties.TargetResourceGroupId = $TargetResourceGroupId
$customProperties.TargetVMName = $TargetVMName
$customProperties.IsDynamicRam = if ($HasIsDynamicMemoryEnabled) { $isDynamicRamEnabled } else { $isSourceDynamicMemoryEnabled }
if ($HasMigrateAsArcVM) {
$customProperties.MigrateAsArcVM = $migrateAsArcVMEnabled
}
# Determine target VM Hyper-V Generation
if ($SiteType -eq $SiteTypes.HyperVSites) {
# Hyper-V source
$customProperties.HyperVGeneration = $machine.Generation
}
else {
#Vmware source, non-BOIS VMs will be migrated to Gen2
$customProperties.HyperVGeneration = if ($machine.Firmware -ieq "BIOS") { "1" } else { "2" }
}
# Validate TargetVMCPUCore
if ($HasTargetVMCPUCore)
{
if ($TargetVMCPUCore -lt $TargetVMCPUCores.Min -or $TargetVMCPUCore -gt $TargetVMCPUCores.Max)
{
throw "Specify -TargetVMCPUCore between $($TargetVMCPUCores.Min) and $($TargetVMCPUCores.Max)."
}
$customProperties.TargetCpuCore = $TargetVMCPUCore
}
else
{
$customProperties.TargetCpuCore = $machine.NumberOfProcessorCore
}
# Validate TargetVMRam
if ($HasTargetVMRam)
{
if ($customProperties.HyperVGeneration -eq "1") {
# Between 512 MB and 1 TB
if ($TargetVMRam -lt $TargetVMRamInMB.Gen1Min -or $TargetVMRam -gt $TargetVMRamInMB.Gen1Max)
{
throw "Specify -TargetVMRAM between $($TargetVMRamInMB.Gen1Min) and $($TargetVMRamInMB.Gen1Max) MB (i.e., 1 TB) for Hyper-V Generation 1 VM."
}
}
else # Hyper-V Generation 2
{
# Between 32 MB and 12 TB
if ($TargetVMRam -lt $TargetVMRamInMB.Gen2Min -or $TargetVMRam -gt $TargetVMRamInMB.Gen2Max)
{
throw "Specify -TargetVMRAM between $($TargetVMRamInMB.Gen2Min) and $($TargetVMRamInMB.Gen2Max) MB (i.e., 12 TB) for Hyper-V Generation 2 VM."
}
}
$customProperties.TargetMemoryInMegaByte = $TargetVMRam
}
else
{
$customProperties.TargetMemoryInMegaByte = [System.Math]::Max($machine.AllocatedMemoryInMB, $RAMConfig.MinTargetMemoryInMB)
}
# Construct default dynamic memory config
$memoryConfig = [Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.ProtectedItemDynamicMemoryConfig]::new()
$memoryConfig.MinimumMemoryInMegaByte = [System.Math]::Min($customProperties.TargetMemoryInMegaByte, $RAMConfig.DefaultMinDynamicMemoryInMB)
$memoryConfig.MaximumMemoryInMegaByte = [System.Math]::Max($customProperties.TargetMemoryInMegaByte, $RAMConfig.DefaultMaxDynamicMemoryInMB)
$memoryConfig.TargetMemoryBufferPercentage = $RAMConfig.DefaultTargetMemoryBufferPercentage
$customProperties.DynamicMemoryConfig = $memoryConfig
# Disks and Nics
[PSCustomObject[]]$disks = @()
[PSCustomObject[]]$nics = @()
if ($parameterSet -match 'DefaultUser') {
if ($SiteType -eq $SiteTypes.HyperVSites) {
$osDisk = $machine.Disk | Where-Object { $_.InstanceId -eq $OSDiskID }
if ($null -eq $osDisk) {
throw "No Disk found with InstanceId $OSDiskID from discovered machine disks."
}
}
elseif ($SiteType -eq $SiteTypes.VMwareSites) {
$osDisk = $machine.Disk | Where-Object { $_.Uuid -eq $OSDiskID }
if ($null -eq $osDisk) {
throw "No Disk found with Uuid $OSDiskID from discovered machine disks."
}
}
foreach ($sourceDisk in $machine.Disk) {
$diskId = if ($SiteType -eq $SiteTypes.HyperVSites) { $sourceDisk.InstanceId } else { $sourceDisk.Uuid }
$diskSize = if ($SiteType -eq $SiteTypes.HyperVSites) { $sourceDisk.MaxSizeInByte } else { $sourceDisk.MaxSizeInBytes }
$DiskObject = [PSCustomObject]@{
DiskId = $diskId
DiskSizeGb = [long] [Math]::Ceiling($diskSize / 1GB)
DiskFileFormat = "VHDX"
IsDynamic = $true
IsOSDisk = $diskId -eq $OSDiskID
}
$disks += $DiskObject
}
foreach ($sourceNic in $machine.NetworkAdapter) {
$NicObject = [PSCustomObject]@{
NicId = $sourceNic.NicId
TargetNetworkId = $TargetVirtualSwitchId
TestNetworkId = if ($HasTargetTestVirtualSwitchId) { $TargetTestVirtualSwitchId } else { $TargetVirtualSwitchId }
SelectionTypeForFailover = $VMNicSelection.SelectedByUser
}
$nics += $NicObject
}
}
else
{
# PowerUser
if ($null -eq $DiskToInclude -or $DiskToInclude.length -eq 0) {
throw "Invalid DiskToInclude. At least one disk is required."
}
# Validate OSDisk is set.
$osDisk = $DiskToInclude | Where-Object { $_.IsOSDisk }
if (($null -eq $osDisk) -or ($osDisk.length -ne 1)) {
throw "Invalid DiskToInclude. One disk must be designated as the OS disk."
}
# Validate DiskToInclude
[PSCustomObject[]]$uniqueDisks = @()
foreach ($disk in $DiskToInclude) {
# Enforce VHDX for Gen2 VMs
if ($customProperties.HyperVGeneration -eq "2" -and $disk.DiskFileFormat -eq "VHD") {
throw "Please specify 'VHDX' as Format for the disk with id '$($disk.DiskId)' in -DiskToInclude by re-running New-AzMigrateLocalDiskMappingObject."
}
# PhysicalSectorSize must be 512 for VHD format if it is set
if ($disk.DiskFileFormat -eq "VHD" -and $null -ne $disk.DiskPhysicalSectorSize -and $disk.DiskPhysicalSectorSize -ne 512) {
throw "Invalid Physical sector size of $($disk.DiskPhysicalSectorSize) is found for VHD format. Please replace disk with id '$($disk.DiskId)' in -DiskToInclude by re-running New-AzMigrateLocalDiskMappingObject with 512 as -PhysicalSectorSize."
}
if ($SiteType -eq $SiteTypes.HyperVSites) {
$discoveredDisk = $machine.Disk | Where-Object { $_.InstanceId -eq $disk.DiskId }
if ($null -eq $discoveredDisk) {
throw "No Disk found with InstanceId '$($disk.DiskId)' from discovered machine disks."
}
}
elseif ($SiteType -eq $SiteTypes.VMwareSites) {
$discoveredDisk = $machine.Disk | Where-Object { $_.Uuid -eq $disk.DiskId }
if ($null -eq $discoveredDisk) {
throw "No Disk found with Uuid '$($disk.DiskId)' from discovered machine disks."
}
}
if ($uniqueDisks.Contains($disk.DiskId)) {
throw "The disk id '$($disk.DiskId)' is already taken."
}
$uniqueDisks += $disk.DiskId
$htDisk = @{}
$disk.PSObject.Properties | ForEach-Object { $htDisk[$_.Name] = $_.Value }
$disks += [PSCustomObject]$htDisk
}
# Validate NicToInclude
[PSCustomObject[]]$uniqueNics = @()
foreach ($nic in $NicToInclude) {
$discoveredNic = $machine.NetworkAdapter | Where-Object { $_.NicId -eq $nic.NicId }
if ($null -eq $discoveredNic) {
throw "The Nic id '$($nic.NicId)' is not found."
}
if ($uniqueNics.Contains($nic.NicId)) {
throw "The Nic id '$($nic.NicId)' is already included. Please remove the duplicate entry and try again."
}
$uniqueNics += $nic.NicId
$htNic = @{}
$nic.PSObject.Properties | ForEach-Object { $htNic[$_.Name] = $_.Value }
if ($htNic.SelectionTypeForFailover -eq $VMNicSelection.SelectedByUser -and
[string]::IsNullOrEmpty($htNic.TargetNetworkId)) {
throw throw "The TargetVirtualSwitchId parameter is required when the CreateAtTarget flag is set to 'true'. NIC '$($htNic.NicId)'. Please utilize the New-AzMigrateLocalNicMappingObject command to properly create a Nic mapping object."
}
$nics += [PSCustomObject]$htNic
}
}
if ($SiteType -eq $SiteTypes.HyperVSites) {
$customProperties.DisksToInclude = [Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.HyperVToAzStackHcidiskInput[]]$disks
$customProperties.NicsToInclude = [Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.HyperVToAzStackHcinicInput[]]$nics
}
elseif ($SiteType -eq $SiteTypes.VMwareSites) {
$customProperties.DisksToInclude = [Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.VMwareToAzStackHcidiskInput[]]$disks
$customProperties.NicsToInclude = [Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20260201.VMwareToAzStackHcinicInput[]]$nics
}
$protectedItemProperties.CustomProperty = $customProperties
# Remove common ErrorVariable and ErrorAction for get behaviors
$null = $PSBoundParameters.Remove('ErrorVariable')
$null = $PSBoundParameters.Remove('ErrorAction')
if ($PSCmdlet.ShouldProcess($MachineId, "Replicate VM.")) {
# Create protected item with ResourceGroupName, VaultName, Name, Property
$null = $PSBoundParameters.Add('Name', $MachineName)
$null = $PSBoundParameters.Add('Property', $protectedItemProperties)
$null = $PSBoundParameters.Add('NoWait', $true)
$operation = Az.Migrate.Internal\New-AzMigrateProtectedItem @PSBoundParameters
$null = $PSBoundParameters.Remove('NoWait')
$null = $PSBoundParameters.Remove('Property')
$null = $PSBoundParameters.Remove('Name')
# Get job with ResourceGroupName, VaultName, Name
$jobName = $operation.Target.Split("/")[-1].Split("?")[0].Split("_")[0]
$null = $PSBoundParameters.Add('Name', $jobName)
return Az.Migrate.Internal\Get-AzMigrateLocalReplicationJob @PSBoundParameters
}
}
}