Repair-AzVM.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
#### BEGIN CONSTANTS ####

#### END CONSTANTS ####

#### BEGIN FUNCTIONS ####

function Repair-AzVM
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true,
            HelpMessage='Name of the Problem VM.')]
        [String] $VMname,

        [Parameter(Mandatory=$true, 
            HelpMessage='RG of the Problem VM')]
        [String] $RGname,
    
        [Parameter(Mandatory=$false)]
        [Validateset('Win2012R2Datacenter','Win2016Datacenter','Win2019Datacenter')]
        [string]$OSVersion = "Win2019Datacenter"
    )
    try
    {
        $StartTime = $(get-date)
        $vm = Get-AzVM -ResourceGroupName $RGname -Name $VMname
        $diskname = $vm.StorageProfile.OsDisk.Name
        $disk = Get-AzDisk | ? {$_.Name -eq $diskname}
        $rvmName = 'Repair-VM'+(Get-Random -Maximum 100)
        $RrgName = 'Repair-VM-RG'+(Get-Random -Maximum 100)
        $vnet = ('Rep-'+$VMname+'-vnet').Trim()
        $nsg = ('Rep-'+$VMname+'-NSG').Trim()
        $pip =('Rep-'+$VMname+'-pip').Trim()
        $location = $vm.Location
        $encryption = $disk.EncryptionSettingsCollection.Enabled
        

#encryption check
        $elapsedTime = $(get-date) - $StartTime
        $total = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
if($encryption -eq $true){
        $keyurl = $disk.EncryptionSettingsCollection.EncryptionSettings.KeyEncryptionKey.KeyUrl
        $secret = $disk.EncryptionSettingsCollection.EncryptionSettings.DiskEncryptionKey.SecretUrl
        $fileuri = @("https://120061622000248sr.blob.core.windows.net/encrypted/install.ps1")
        $finaloutput = "Hyper-V enabled,Unlocking disk now & VM will be restarted later"
        Write-Host "$total The VM is encrypted. the disk will be unlocked at the target" -ForegroundColor Yellow
        }else{
        $fileuri = @("https://120061622000248sr.blob.core.windows.net/script/install.ps1")
        $finaloutput = "Hyper-V enabled & restarted, please wait until the VM is back online"
        Write-Host "$total No encryption proceeding with Repair VM creation" -ForegroundColor Green
        }

#create Repaair VM
    $create = New-AzVm `
    -ResourceGroupName $RrgName `
    -Name $rvmName `
    -Location $location `
    -VirtualNetworkName $vnet `
    -SubnetName "default" `
    -SecurityGroupName $nsg `
    -PublicIpAddressName $pip `
    -OpenPorts 3389 -Size Standard_D4s_v3 -Image $OSVersion
$elapsedTime = $(get-date) - $StartTime
$total = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
Write-Host "$total Repair VM is created" -ForegroundColor Green
Write-Host "$total Attaching the faulty disk..." -ForegroundColor Yellow

#get OS disk & create copy
    $newdiskname = $vmname+'-osdisk'+(Get-Random -Maximum 100)
    $diskConfig = New-AzDiskConfig -SourceResourceId $disk.Id -Location $disk.Location -CreateOption Copy 
    $newdiskcreate = New-AzDisk -Disk $diskConfig -DiskName $newdiskname -ResourceGroupName $RGname -WarningAction SilentlyContinue
    
#Attach to repair VM
    $rvm = Get-AzVM -Name $rvmName -ResourceGroupName $RrgName
    $rvm = Add-AzVMDataDisk -VM $rvm -CreateOption Attach -ManagedDiskId $newdiskcreate.Id -Lun 1
    Update-AzVM -VM $rvm -ResourceGroupName $RrgName
    $elapsedTime = $(get-date) - $StartTime
    $total = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
    Write-Host "$total Faulty disk attached" -ForegroundColor Green

#Enable Hyper-V
    Write-Host "$total Enabling Hyper-V on $rvmName" -ForegroundColor Yellow
    $settings = @{"fileUris" = $fileUri};
    $protectedSettings = @{"commandToExecute" = "powershell -ExecutionPolicy Unrestricted -File install.ps1"};
    $cse = Set-AzVMExtension -ResourceGroupName $rvm.ResourceGroupName `
    -Location $rvm.Location `
    -VMName $rvm.Name `
    -Name "enablehyperv" `
    -Publisher "Microsoft.Compute" `
    -ExtensionType "CustomScriptExtension" `
    -TypeHandlerVersion "1.10" `
    -Settings $settings    `
    -ProtectedSettings $protectedSettings

$elapsedTime = $(get-date) - $StartTime
$total = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
Write-Host "$total $finaloutput" -ForegroundColor Green
if($encryption -eq $true){
$vault = ($keyurl.Split('/')[2]).split('.')[0]
$KeyVault = Get-AzKeyVault | ? {$_.Vaultname -eq $vault}
$getvault = Get-AzKeyVault -VaultName $vault -ResourceGroupName $KeyVault.ResourceGroupName
$encrypt = Set-AzVMDiskEncryptionExtension -ResourceGroupName $RrgName -VMName $rvmName -DiskEncryptionKeyVaultUrl $getVault.VaultUri -DiskEncryptionKeyVaultId $getvault.ResourceId -VolumeType All -Force
$elapsedTime = $(get-date) - $StartTime
$total = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
Write-Host "$total Disk Unlocked & restarted, Please wait till the VM is back online" -ForegroundColor Green
Start-Sleep -Seconds 20
$elapsedTime = $(get-date) - $StartTime
$total = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
Write-Host "$total Repair VM $rvmName is ready now" -ForegroundColor Green
}else{
Start-Sleep -Seconds 20
$elapsedTime = $(get-date) - $StartTime
$total = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
Write-Host "$total Repair VM $rvmName is ready now" -ForegroundColor Yellow}

}
        catch
    {
        throw
    }
    finally
    {

    }
}
Export-ModuleMember -Function Repair-AzVM
#### END FUNCTIONS ####