MigrateTo-AzureRM.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
function MigrateTo-AzureRM {
     <#
             .SYNOPSIS
             Migrates Azure Classic Virtual Networks, and all dependent resources to Resource Manager.
   
   
             .DESCRIPTION
             Running this command will allow you to migrate a Virtual Network, and the resources within it to Resource Manager.
   
             If you choose not to specify subscription ID's, a Virtual Network Name, Credentials, etc. you will be provided with an interface via the command line.
      
             .PARAMETER AzureCredentials
             You can pass in a credential object to use to sign in to Azure.
              
              
             .PARAMETER RMSubscriptionId
             Used to specify the ID of the subscription you want to migrate your Virtual Network and it's resources to.
              
              
              
             .PARAMETER ClassicSubscriptionId
             Used to specify the ID of the subscription where your Classic resources are located.
              
              
              
             .PARAMETER VirtualNetworkName
             Specify the name of the classic Virtual Network you would like to migrate.
   
               
             .PARAMETER AllVirtualNetworks
             Specify this switch to migrate all virtual networks in the classic subscription.
 
 
             .PARAMETER Force
             Specify this switch to automatically choose "yes" when committing the migration after the migration preparation.
   
   
             .EXAMPLE
                      The following example will run the function silently:
              
             $c = Get-Credential
             MigrateTo-AzureRM -AzureCredentials $c `
                               -RMSubscriptionId e87ec6e6-874c-4295-9ba2-17ddb4bfd911 `
                               -ClassicSubscriptionId e87ec6e6-874c-4295-9ba2-17ddb4bfd911 `
                               -VirtualNetworkName MIG-VNet `
                               -Force
   
             .EXAMPLE
             If you are unsure of what information to pass in to the cmdlet, the following example will provide an interactive interface for the user to provide input:
   
             MigrateTo-AzureVM
   
             #>

    [CmdletBinding(DefaultParameterSetName="SpecifyNetworks")]
    param(
        [System.Management.Automation.PSCredential]
        [parameter(ParameterSetName="AllNetworks")]
        [parameter(ParameterSetName="SpecifyNetwork")]
        $AzureCredentials = (Get-Credential -Message "Please enter Azure credentials"),
        [string]
        [parameter(ParameterSetName="AllNetworks")]
        [parameter(ParameterSetName="SpecifyNetwork")]
        $RMSubscriptionId,
        [string]
        [parameter(ParameterSetName="AllNetworks")]
        [parameter(ParameterSetName="SpecifyNetwork")]
        $ClassicSubscriptionId,
        [string]
        [parameter(ParameterSetName="SpecifyNetwork")]
        $VirtualNetworkName,
        [switch]
        [parameter(ParameterSetName="AllNetworks")]
        $AllVirtualNetworks,
        [switch]
        [parameter(ParameterSetName="AllNetworks")]
        [parameter(ParameterSetName="SpecifyNetwork")]
        $Force
    
    )



    #--------------------------------------------------------------------------------------------------------------------------------------
    # Prepare for Migration
    #--------------------------------------------------------------------------------------------------------------------------------------
    Start-Transcript -Path "$env:temp\MigrateTo-AzureRM\$(Get-Date -Format yyMMddHHmmss).log" | Out-Null
    "Log file stored at: $env:temp\MigrateTo-AzureRM\$(Get-Date -Format yyMMddHHmmss).log"

    if ((Get-Module Azure,AzureRM -ListAvailable).Count -lt 2)
    {
       Write-Error "Make sure you have the Azure & AzureVM modules installed on your workstation, along with their sub-modules. For more informatiom, visit https://github.com/Azure/azure-powershell."
       Stop-Transcript -OutVariable $OutputDump | Out-Null
       break
    }
    elseif ((Get-Module Azure,AzureRM).Count -lt 2)
    {
        Import-Module Azure,AzureRM -ErrorVariable FailedToLoad
        if ($FailedToLoad)
        {
            Write-Error "The modules Azure & AzureRM could not be imported."
            Stop-Transcript -OutVariable $OutputDump | Out-Null
            break
        }
    }

    Clear-AzureProfile -Force

    #--------------------------------------------------------------------------------------------------------------------------------------
    # Azure RM Login
    #--------------------------------------------------------------------------------------------------------------------------------------

    try
    {
        $loggingin = Login-AzureRmAccount -Credential $AzureCredentials
        Write-Host " "
        Write-Host " "
        Write-Host "Logged into tenant $($loggingin.Context.Tenant) using login $($loggingin.Context.Account)" -ForegroundColor Green
    }
    catch
    {
        Write-Host $Error[0].Exception.Message -ForegroundColor Red
        Stop-Transcript -OutVariable $OutputDump | Out-Null
        break
    }

    if ($RMSubscriptionId)
    {
        $RMSubID = $RMSubscriptionId
       
        try
        {
            Select-AzureRmSubscription -SubscriptionId $RMSubID | Out-Null
        }
        catch
        {
            Write-Error "The Azure RM Subscription ID you provided is invalid. Please verify the ID is correct, or specify the function without the `"-RMSubscriptionID`" parameter."
            Stop-Transcript -OutVariable $OutputDump | Out-Null
            break
        }

    }
    else
    {
        $Subscriptions = Get-AzureRmSubscription -WarningAction SilentlyContinue

        if ($Subscriptions.Count -eq 1)
        {
            Select-AzureRmSubscription -SubscriptionId $Subscriptions.SubscriptionId | out-null
            $RMSubID = $Subscriptions.SubscriptionId
        }

        elseif ($Subscriptions.Count -gt 1)
        {

            $SubNum = 1
            Write-host " "
            Write-host "Please choose the Subscription for AZURE RESOURCE MANAGER" -ForegroundColor Yellow
            Write-host "---------------------------------------------------------" -ForegroundColor Yellow
            
            foreach ($Subscription in $Subscriptions)
            {
                Write-host "$($SubNum): " -ForegroundColor Green -NoNewline
                Write-host "$($Subscription.SubscriptionName) ($($Subscription.SubscriptionId))" -ForegroundColor Yellow
                $SubNum++
            }

            Write-host " "
            do
            {
                Write-Host "You have more than one subscription, please enter the number of the subscription you wish to use:" -ForegroundColor Yellow
                $SubOption = Read-host

                if (($SubOption -gt $SubNum) -or ($SubOption -eq 0))
                {
                    Write-Host "That number does not correlate to any of your subscriptions!" -ForegroundColor Red
                }

            } while (($SubOption -gt $SubNum) -or ($SubOption -eq 0))

            Write-host "Using Azure Subscription: $($Subscriptions[($SubOption - 1)].SubscriptionName)" -ForegroundColor Green
            Select-AzureRmSubscription -SubscriptionId $($Subscriptions[($SubOption - 1)].SubscriptionId) | out-null
            $RMSubID = $($Subscriptions[($SubOption - 1)].SubscriptionId)
        }
        else
        {
            Write-Error "You have no Subscriptions"
            Stop-Transcript -OutVariable $OutputDump | Out-Null
            break   
        }

    }


    #--------------------------------------------------------------------------------------------------------------------------------------
    # Azure Classic Login
    #--------------------------------------------------------------------------------------------------------------------------------------
    try
    {
        Add-AzureAccount -Credential $AzureCredentials | out-null
    }
    catch
    {
        Write-Host $Error[0].Exception.Message -ForegroundColor Red
        Stop-Transcript -OutVariable $OutputDump | Out-Null
        break
    }

    if ($ClassicSubscriptionId)
    {
        $CLSubID = $ClassicSubscriptionId

        try
        {
            Select-AzureSubscription -SubscriptionId $CLSubID | Out-Null
        }
        catch
        {
            Write-Error "The Azure Classic Subscription ID you provided is invalid. Please verify the ID is correct, or specify the function without the `"-ClassicSubscriptionID`" parameter."
            Stop-Transcript -OutVariable $OutputDump | Out-Null
            break
        }

    }
    else
    {
        $Subscriptions = Get-AzureSubscription -WarningAction SilentlyContinue

        if ($Subscriptions.Count -eq 1)
        {
            Select-AzureSubscription -SubscriptionId $Subscriptions.SubscriptionId
            $CLSubID = $Subscriptions.SubscriptionId
        }
        elseif ($Subscriptions.Count -gt 1)
        {
            $SubNum = 1
            Write-Host " "
            Write-host "Please choose the Subscription for AZURE CLASSIC" -ForegroundColor Yellow
            Write-host "------------------------------------------------" -ForegroundColor Yellow

            foreach ($Subscription in $Subscriptions)
            {
                Write-host "$($SubNum): " -ForegroundColor Green -NoNewline
                Write-host "$($Subscription.SubscriptionName) ($($Subscription.SubscriptionId))" -ForegroundColor Yellow
                $SubNum++
            }

            Write-host " "

            do
            {
                Write-Host "You have more than one subscription, please enter the number of the subscription you wish to use:" -ForegroundColor Yellow
                $SubOption = Read-host

                if (($SubOption -gt $SubNum) -or ($SubOption -eq 0))
                {
                    Write-Host "That number does not correlate to any of your subscriptions!" -ForegroundColor Red
                }
                else
                {
                    Write-host "Using Azure Subscription: $($Subscriptions[($SubOption - 1)].SubscriptionName)" -ForegroundColor Green
                    Select-AzureSubscription -SubscriptionId $($Subscriptions[($SubOption - 1)].SubscriptionId)
                    $CLSubID = $($Subscriptions[($SubOption - 1)].SubscriptionId)
                }

            } while (($SubOption -gt $SubNum) -or ($SubOption -eq 0))

        }
        else
        {
            Write-Error "You have no Subscriptions"
            Stop-Transcript -OutVariable $OutputDump | Out-Null
            break
        }
    }



    #--------------------------------------------------------------------------------------------------------------------------------------
    # Register Subscriptions to required namespace
    #--------------------------------------------------------------------------------------------------------------------------------------
    $RegisterUpdate = $false
    Write-Host " "
    Write-Host "Checking ProviderNamespace Registration for selected subscriptions..." -ForegroundColor Yellow

    foreach ($ID in ($RMSubID,$CLSubID))
    {
        Select-AzureRmSubscription -SubscriptionId $ID | Out-Null

        if (!((Get-AzureRmResourceProvider -ProviderNamespace Microsoft.ClassicInfrastructureMigrate).RegistrationState -eq "Registered"))
        {
            Register-AzureRmResourceProvider -ProviderNamespace Microsoft.ClassicInfrastructureMigrate -Force
            $RegisterUpdate = $true
        }

    }

    if ($RegisterUpdate)
    {
        Write-Host " "
        Write-Host "One or more ProvideNamespaces required registration, waiting for registration to propogate..." -ForegroundColor Yellow
        $percentage = 0.16666666666666666666666666666667

        for ($a=1; $a -lt 600; $a++)
        {
            $percentage += 0.16666666666666666666666666666667
            Write-Progress -Activity "Updating Microsoft.ClassicInfrastructureMigrate Registration..." -SecondsRemaining $(600 - $a) -PercentComplete $percentage -Status "Updating..."
            Start-Sleep 1
        }

        Write-Progress -Activity "Updating Microsoft.ClassicInfrastructureMigrate Registration..." -Completed -Status "Updated."
    }

    Select-AzureRmSubscription -SubscriptionId $RMSubID | Out-Null



    #--------------------------------------------------------------------------------------------------------------------------------------
    # Virtual Network selection
    #--------------------------------------------------------------------------------------------------------------------------------------

    $VNets = Get-AzureVNetSite
    $VirtualNetworks = $null
    if (!$VNets)
    {
        Write-Error "No Classic Virtual Networks were found under the subscription $((Get-AzureSubscription -SubscriptionId $CLSubID).SubscriptionName) ($CLSubID)"
        Stop-Transcript -OutVariable $OutputDump | Out-Null
        break
    }
    elseif ($AllVirtualNetworks)
    {
        $VirtualNetworks = $VNets.Name
    }
    elseif (($VirtualNetworkName -ne $null) -and ($VNets | ? { $_.Name -ieq $VirtualNetworkName}))
    {
        $VirtualNetworks = $VirtualNetworkName
    }
    elseif (($VirtualNetworkName -eq $null) -and ($AllVirtualNetworks -eq $null))
    {
        $VNetNum = 1
        Write-Host " "
        Write-host "Which Virtual Network would you like to migrate?" -ForegroundColor Yellow
        Write-host "------------------------------------------------" -ForegroundColor Yellow

        foreach ($VNet in $VNets)
        {
            Write-host "$($VNetNum): " -ForegroundColor Green -NoNewline
            Write-host "$($VNet.Name) ($($VNet.Location))" -ForegroundColor Yellow
            $VNetNum++
        }

        Write-host " "

        do
        {
            Write-Host "You have more than one Virtual Network, please enter the number of the Virtual Network you wish to migrate:" -ForegroundColor Yellow
            $VNetOption = Read-host

            if (($VNetOption -gt $VNetNum) -or ($VNetOption -eq 0))
            {
                Write-Host "That number does not correlate to any of your Virtual Networks!" -ForegroundColor Red
            }
            else
            {
                $VirtualNetworks = "$($VNets[($VNetOption - 1)].Name)"
            }

        } while (($VNetOption -gt $VNetNum) -or ($VNetOption -eq 0))

    }
    else
    {
        Write-Error "The Virtual Network Name you specified is not recognised."
    }



    #--------------------------------------------------------------------------------------------------------------------------------------
    # Migrate Virtual Network
    #--------------------------------------------------------------------------------------------------------------------------------------

    foreach ($VirtualNetwork in $VirtualNetworks)
    {
            Write-Host " "
            Write-host "Preparing for migration of Azure Virtual Network $VirtualNetwork..." -ForegroundColor Yellow
            Write-Host " "
            Write-Host "VERBOSE LOG" -ForegroundColor Cyan
            Move-AzureVirtualNetwork -Prepare -VirtualNetworkName $VirtualNetwork -Verbose
            Write-Host " "

            if ($?)
            {
                Write-Host "Preparation Complete." -ForegroundColor Green
            }
            else
            {
                $Error[0]
                Write-Host "Navigate to the Resource Group `'<Name of Failed Resource>-Migrated`' to view the deployment log for any failures." -ForegroundColor Red
                Stop-Transcript -OutVariable $OutputDump | Out-Null
                break
            }

    }

    do
    {

        if (!$Force)
        {
            Write-Host "The Virtual Network is now ready to be moved. Would you like to continue? (y/n)" -ForegroundColor Yellow
            $MoveOption = Read-Host 
        }
        else
        {
            $MoveOption = 'y'
        }

        if ($MoveOption -ieq "y")
        {
            Write-Host "Committing Migration..." -ForegroundColor Yellow
            Write-Host " "
            Write-Host "VERBOSE LOG" -ForegroundColor Cyan
            Move-AzureVirtualNetwork -Commit -VirtualNetworkName $($VNets[($VNetOption - 1)].Name) -Verbose
            Write-Host " "
        }
        elseif ($MoveOption -ieq "n")
        {
            Write-Host "Aborting Migration..." -ForegroundColor Yellow
            Write-Host " "
            Write-Host "VERBOSE LOG" -ForegroundColor Cyan
            Move-AzureVirtualNetwork -Abort -VirtualNetworkName $($VNets[($VNetOption - 1)].Name) -Verbose
            Write-Host " "
        }
        else
        {
            Write-Host "You did not provide a valid option!" -ForegroundColor Red
        }

    } while (($MoveOption -ine "y") -and ($MoveOption -ine "n"))
    Stop-Transcript -OutVariable $OutputDump | Out-Null
} 

Export-ModuleMember -Function MigrateTo-AzureRM