Repair-AzVM.psm1

#### BEGIN CONSTANTS ####

#### END CONSTANTS ####

#### BEGIN FUNCTIONS ####


function Repair-AzVM
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true,
            HelpMessage='A VM object that is represented by a row in an Excel file.')]
        [String] $VMname,

        [Parameter(Mandatory=$true, 
            HelpMessage='Path to a text file that will contain the IP of the server passed in at $VmSettings.')]
        [String] $RGname

    )

    try
    {
        $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
if($encryption -eq $true){
        $keyurl = $disk.EncryptionSettingsCollection.EncryptionSettings.KeyEncryptionKey.KeyUrl
        $secret = $disk.EncryptionSettingsCollection.EncryptionSettings.DiskEncryptionKey.SecretUrl
        Write-Host "The VM is encrypted. the disk will be unlocked at the target" -ForegroundColor Yellow
        }else{
        Write-Host "No encryption proceeding with 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

Write-Host "Repair VM is created" -ForegroundColor Green
Write-Host "Attching 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
    Write-Host "Faulty disk attached" -ForegroundColor Green

#unlocking the disk if encrypted
if($encryption -eq $true){
$vault = ($keyurl.Split('/')[2]).split('.')[0]
$KeyVault = Get-AzKeyVault | ? {$_.Vaultname -eq $vault}
$getvault = Get-AzKeyVault -VaultName $vault -ResourceGroupName $KeyVault.ResourceGroupName
Write-Host "Unlocking disk" -ForegroundColor Yellow
$encrypt = Set-AzVMDiskEncryptionExtension -ResourceGroupName $RrgName -VMName $rvmName -DiskEncryptionKeyVaultUrl $getVault.VaultUri -DiskEncryptionKeyVaultId $getvault.ResourceId -VolumeType All -Force
}else{
Write-Host "Skipping encryption" -ForegroundColor Yellow}

#vm online check
do{
$K = 1
$ip = (Get-AzPublicIpAddress -Name $pip -ResourceGroupName $RrgName).IpAddress
$connection = Test-NetConnection -ComputerName $ip -Port 3389 -WarningAction SilentlyContinue
if($connection.TcpTestSucceeded -eq $true){
Write-Host "Unlocked, VM Online now." -ForegroundColor Green}
else{
Write-Host "Waiting for VM" -ForegroundColor Yellow
$k= 0}
}
while($k -eq 0)

#Enable Hyper-V
    Write-Host "Enabling Hyper-V on $rvmName" -ForegroundColor Yellow
    $fileUri = @("https://120061622000248sr.blob.core.windows.net/script/install.ps1")
    $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

Write-Host "Hyper-V enabled & restarted, please wait till the VM is back online" -ForegroundColor Green
do{
$K = 1
$ip = (Get-AzPublicIpAddress -Name $pip -ResourceGroupName $RrgName).IpAddress
$connection = Test-NetConnection -ComputerName $ip -Port 3389 -WarningAction SilentlyContinue
if($connection.TcpTestSucceeded -eq $true){
Write-Host "Repair VM $rvmName is ready now" -ForegroundColor Green}
else{
Write-Host "Waiting for VM" -ForegroundColor Yellow
$k= 0}
}
while($k -eq 0)

    }
        catch
    {
        throw
    }
    finally
    {

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