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,

        [Parameter(Mandatory=$false,
            HelpMessage='Do a fast build and skip software installation and domain joining; otherwise do a normal build. Speeds up the testing process.')]
        [Switch] $DoFastBuild
    )

    try
    {
        $vm = Get-AzVM -ResourceGroupName $RGname -Name $VMname
        $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
#create Repaair VM
     New-AzVm `
    -ResourceGroupName $RrgName `
    -Name $rvmName `
    -Location $location `
    -VirtualNetworkName $vnet `
    -SubnetName "default" `
    -SecurityGroupName $nsg `
    -PublicIpAddressName $pip `
    -OpenPorts 3389 -Size Standard_D4s_v3
    

#get OS disk & create copy
    $diskname = $vm.StorageProfile.OsDisk.Name
    $disk = Get-AzDisk | ? {$_.Name -eq $diskname}
    $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
    
#enable Hyper-V

    $fileUri = @("https://120061622000248sr.blob.core.windows.net/script/install.ps1")
    $settings = @{"fileUris" = $fileUri};
    $protectedSettings = @{"commandToExecute" = "powershell -ExecutionPolicy Unrestricted -File install.ps1"};
    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

#Start-Sleep -Seconds 20
#check VM status
#do{
#$vmcheck = Test-NetConnection -ComputerName 52.136.113.150 -Port 3389
#if($vmcheck.TcpTestSucceeded = true){
#mstsc /v:10.10.10.10:3389
    }
        catch
    {
        throw
    }
    finally
    {

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