none
Powershell code for custom VHD with VM

    Question

  • I have my own custom VHD...how i can create new VM in Azure Portal and attach the existing VHD to that VM....any Poweshell code or advise to that?

    Tariq Younas

    Monday, August 15, 2016 10:26 AM

Answers

  • Hi,

    Adding some comments to Sadiqh Ahmed response, this script could help you to go straight forward on migrating VHD´s and create either disk or VM image: 

    #**********************
    # Variables
    #*********************
    $Subscription = "[Your Subscription]"
    $SubscriptionId = "[Your SubscriptionId xxxx-xxxx-xxx]"
    $StorageAccountName = '[yourstorageaccountname]'
    $Location = 'East Us'
    $ContainerName = "[yourcontainername]"
    $LocalVHD = "C:\Users\Dave\Dropbox\KEMP\VLM-trial\LoadMasterVLM.vhd"
    $AzureVHD = "https://yourstorageaccountname.blob.core.windows.net/yourcontainername/LoadMasterVLM.vhd"
    $DiskName = 'LoadMaster-Hyper-V'
    $LabelName = 'LoadMaster-Hyper-V'
    $VMImageName = "LoadMaster"
    # *************************************
    # Prepare the access to your subscription
    #**************************************
    #Login to Azure Subscription
    Add-AzureAccount
    # List Available Windows Azure subscriptions
    Get-AzureSubscription | Format-Table -Property SubscriptionName
    #Set default Windows Azure subscription 
    Select-AzureSubscription -SubscriptionId $SubscriptionId -Default
    # Create a new storage account.
    New-AzureStorageAccount –StorageAccountName $StorageAccountName -Location $Location
    # Set a default storage account.
    Set-AzureSubscription -CurrentStorageAccountName $StorageAccountName -SubscriptionName $Subscription
    # Create a new container.
    New-AzureStorageContainer -Name $ContainerName -Permission Off
    # Get default Windows Azure Storage Account.
    Get-AzureStorageAccount | Format-Table -Property Label
    # Identify where the VHD is coming from and where it's going.
    Add-AzureVhd -LocalFilePath $LocalVHD -Destination $AzureVHD
    #Add the VHD to the “My Disk” section of the Gallery
    # Register as an OS disk 
    Add-AzureDisk -DiskName $DiskName -MediaLocation $AzureVHD -Label $LabelName -OS Windows
    #If you want to create the image
    Add-AzureVMImage -ImageName $VMImageName -MediaLocation $AzureVHD -OS Windows

    Just my 2 cents


    David Rendón @DaveRndn

    • Marked as answer by Tariq Younas Tuesday, August 16, 2016 1:03 AM
    Monday, August 15, 2016 8:06 PM
  • Hi Tariq,

    You could migrate your VHD.

    You have 2 options:

    1) register the vm as OS Disk - you can use it only 1 time, and you should be careful when you attach the disk to another VM

    # Register as an OS disk
    Add-AzureDisk -DiskName $DiskName -MediaLocation $AzureVHD -Label $LabelName -OS Windows

    2) you can use the VHD as image to replicate multiple VM´s

    #to create the image

    Add-AzureVMImage -ImageName $VMImageName -MediaLocation $AzureVHD -OS Windows

    Best regards!


    David Rendón @DaveRndn

    • Marked as answer by Tariq Younas Tuesday, August 16, 2016 9:02 PM
    Tuesday, August 16, 2016 5:07 PM
  • Indeed, Azure Service Management, there is a good lecture around it: https://blog.kloud.com.au/2016/04/05/azure-classic-vs-azure-resource-manager/

    David Rendón @DaveRndn

    • Marked as answer by Tariq Younas Wednesday, August 17, 2016 9:37 PM
    Wednesday, August 17, 2016 9:19 PM
  • Hi Tariq,

    After some testing, you could try this script, tried to make it as simple as possible, in this example you could deploy a single VM vía Resource Manager, adding some vnet/subnet configuration, public IP Address, NIC, 

    Consider to use the cmdlet: Login-AzureRmAccount and Select-AzureRmSubscription before running the script

    You can modify it to your own vhd purposes:

    #************************
    # Deploy VM via ARM
    # Author:@DaveRndn
    # http://wikiazure.com
    #***********************
    
    
    $Location = "West US"
    $ResourceGroupName = "TestDeployARM"
    $SubnetName = "Subnet-1"
    $TestName = "testdeployarm1"
    $VnetName = "VnetTestDeployARM"
    $Publisher = "MicrosoftWindowsServer"
    $Offer = "WindowsServer"
    $Sku = "2012-R2-Datacenter"
    $Version = "latest"
    
    
    New-AzureRmResourceGroup -Name $ResourceGroupName -Location $Location
    
    New-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $TestName -Location $Location -Type Standard_LRS
    
    $Subnet = New-AzureRmVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix "10.0.64.0/24"
    
    $Vnet = New-AzureRmVirtualNetwork -Name $VnetName -ResourceGroupName $ResourceGroupName -Location $Location -AddressPrefix "10.0.0.0/16" -Subnet $Subnet
    
    $Subnet = Get-AzureRmVirtualNetworkSubnetConfig -Name $SubnetName -VirtualNetwork $Vnet
    
    
    $PublicIpAdress = New-AzureRmPublicIpAddress -ResourceGroupName $ResourceGroupName -Name "VipTstARM" -Location $Location -AllocationMethod Dynamic -DomainNameLabel $TestName
    
    $Nic = New-AzureRmNetworkInterface -ResourceGroupName $ResourceGroupName -Name "Nic1tst" -Subnet $Subnet -Location $Location -PublicIpAddress $PublicIpAdress -PrivateIpAddress "10.0.64.4"
    
    $Cred = Get-Credential
    
    $VmConfig = New-AzureRmVMConfig -VMName "VM1" -VMSize "Standard_A1"  | 
                Set-AzureRmVMOperatingSystem -Windows -ComputerName "VM1" -Credential $Cred -ProvisionVMAgent -EnableAutoUpdate |
                Set-AzureRmVMSourceImage -PublisherName $Publisher -Offer $Offer -Skus $Sku -Version $Version |
                Set-AzureRmVMOSDisk -Name "$TestName-v1" -VhdUri "https://testdeployarm1.blob.core.windows.net/vhd/$TestName-v1.vhd" -Caching ReadWrite -CreateOption fromImage |
                Add-AzureRmVMNetworkInterface -Id $Nic.Id
    
    New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $Location -VM $VmConfig

    Best regards!


    Dave Rendón @DaveRndn



    Tuesday, August 23, 2016 11:06 PM
  • Hi Tariq, 

    Not sure if there was a merge in last comments... 

    about the storage, you could check if the blob already exists: 

    try
    {   
        $blob = Get-AzureStorageBlob -Blob $azureBlobName -Container $azureStorageContainer -Context $azureContext -ErrorAction Stop
    }
    catch [Microsoft.WindowsAzure.Commands.Storage.Common.ResourceNotFoundException]
    {
        # Add logic here to remember that the blob doesn't exist...
        Write-Host "Blob Not Found"
    }
    catch
    {
        # Report any other error
        Write-Error $Error[0].Exception;
    }

    An easier way to check try the http://storageexplorer.com/

    The best way is to migrate it vía ASM with the 1st script and then deploy the VM using 2nd, 

    $VMConfig = Set-AzureRmVMOperatingSystem -VM $VirtualMachine -Windows -ComputerName $ComputerName -Credential $Cred -ProvisionVMAgent -EnableAutoUpdate
    $VMConfig = Set-AzureRmVMSourceImage -VM $VirtualMachine

    Perhaps this examples might also help: https://msdn.microsoft.com/en-us/library/mt603754.aspx


    David Rendón @DaveRndn

    • Marked as answer by Tariq Younas Wednesday, August 24, 2016 1:54 AM
    Tuesday, August 23, 2016 11:53 PM

All replies

  • Hi Tariq,

    Thank you for posting in Azure forums!

    You need to create a storage account and upload your VHD to Azure.

    See the link for instructions - https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-windows-classic-createupload-vhd/ 

    Also refer to the below links, you might find helpful.

    http://stackoverflow.com/questions/35327590/create-vm-from-existing-vhd-preview-portal
    http://stackoverflow.com/questions/20833563/how-to-create-new-vm-using-the-existing-vhd-in-the-azure-blob-storage

    Best Regards

    Sadiqh Ahmed
    ________________________________________________________________________________________________________________

    If this post was helpful to you, please upvote it and/or mark it as an answer so others can more easily find it in the future.

    Monday, August 15, 2016 7:25 PM
    Moderator
  • Hi,

    Adding some comments to Sadiqh Ahmed response, this script could help you to go straight forward on migrating VHD´s and create either disk or VM image: 

    #**********************
    # Variables
    #*********************
    $Subscription = "[Your Subscription]"
    $SubscriptionId = "[Your SubscriptionId xxxx-xxxx-xxx]"
    $StorageAccountName = '[yourstorageaccountname]'
    $Location = 'East Us'
    $ContainerName = "[yourcontainername]"
    $LocalVHD = "C:\Users\Dave\Dropbox\KEMP\VLM-trial\LoadMasterVLM.vhd"
    $AzureVHD = "https://yourstorageaccountname.blob.core.windows.net/yourcontainername/LoadMasterVLM.vhd"
    $DiskName = 'LoadMaster-Hyper-V'
    $LabelName = 'LoadMaster-Hyper-V'
    $VMImageName = "LoadMaster"
    # *************************************
    # Prepare the access to your subscription
    #**************************************
    #Login to Azure Subscription
    Add-AzureAccount
    # List Available Windows Azure subscriptions
    Get-AzureSubscription | Format-Table -Property SubscriptionName
    #Set default Windows Azure subscription 
    Select-AzureSubscription -SubscriptionId $SubscriptionId -Default
    # Create a new storage account.
    New-AzureStorageAccount –StorageAccountName $StorageAccountName -Location $Location
    # Set a default storage account.
    Set-AzureSubscription -CurrentStorageAccountName $StorageAccountName -SubscriptionName $Subscription
    # Create a new container.
    New-AzureStorageContainer -Name $ContainerName -Permission Off
    # Get default Windows Azure Storage Account.
    Get-AzureStorageAccount | Format-Table -Property Label
    # Identify where the VHD is coming from and where it's going.
    Add-AzureVhd -LocalFilePath $LocalVHD -Destination $AzureVHD
    #Add the VHD to the “My Disk” section of the Gallery
    # Register as an OS disk 
    Add-AzureDisk -DiskName $DiskName -MediaLocation $AzureVHD -Label $LabelName -OS Windows
    #If you want to create the image
    Add-AzureVMImage -ImageName $VMImageName -MediaLocation $AzureVHD -OS Windows

    Just my 2 cents


    David Rendón @DaveRndn

    • Marked as answer by Tariq Younas Tuesday, August 16, 2016 1:03 AM
    Monday, August 15, 2016 8:06 PM
  • Wonderful !

    David: Let me try this.

    More Questions:

    1. Can i upload win server 2008.vhd using following script

    2. what is meaning of last comment (#If you want to create the image)...do i need to run this also?


    Tariq Younas

    Tuesday, August 16, 2016 1:04 AM
  • Hi Tariq,

    You could migrate your VHD.

    You have 2 options:

    1) register the vm as OS Disk - you can use it only 1 time, and you should be careful when you attach the disk to another VM

    # Register as an OS disk
    Add-AzureDisk -DiskName $DiskName -MediaLocation $AzureVHD -Label $LabelName -OS Windows

    2) you can use the VHD as image to replicate multiple VM´s

    #to create the image

    Add-AzureVMImage -ImageName $VMImageName -MediaLocation $AzureVHD -OS Windows

    Best regards!


    David Rendón @DaveRndn

    • Marked as answer by Tariq Younas Tuesday, August 16, 2016 9:02 PM
    Tuesday, August 16, 2016 5:07 PM
  • Great...Thanks Dave.

    Tariq Younas

    Tuesday, August 16, 2016 9:02 PM
  • Thanks Sadiqh Ahmed...your information is also very useful.

    Tariq Younas

    Tuesday, August 16, 2016 9:03 PM
  • Hi Dave,

    Getting this warning as well.


    Tariq Younas

    Tuesday, August 16, 2016 11:11 PM
  • Hi Tariq, 

    You can bypass that warning, is just related to the current Azure Subscription you are working with, let me know if you get any other warning/issue

    Regards!


    David Rendón @DaveRndn

    Wednesday, August 17, 2016 12:06 AM
  • Hi David,

    Yes, end if script i got this  "The VHD must be stored as a page blob"


    Tariq Younas

    Wednesday, August 17, 2016 12:51 AM
  • Hi Dave,

    Its working fine now :) I was uploading VM manually from Visual studio which was causing error....now custom VM is working perfectly fine :)  Thanks.

    One More Question: This VM is in classic mode...can we create this VM in Resource Group using latest one?


    Tariq Younas

    Wednesday, August 17, 2016 10:52 AM
  • Hi Tariq, 

    Awesome! Glad to hear is working fine. As of today, would be better to migrate via ASM, and then Migrate IaaS resources from classic to Azure Resource Manager thru PowerShell (https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-windows-ps-migration-classic-resource-manager/)

    Another approach would be to create the Networking configuration and then deploy the VM thru ARM, that implies more manual work as well


    David Rendón @DaveRndn

    Wednesday, August 17, 2016 4:37 PM
  • Thanks for article...ASM stand for Azure service manager?

    Tariq Younas

    Wednesday, August 17, 2016 9:09 PM
  • Indeed, Azure Service Management, there is a good lecture around it: https://blog.kloud.com.au/2016/04/05/azure-classic-vs-azure-resource-manager/

    David Rendón @DaveRndn

    • Marked as answer by Tariq Younas Wednesday, August 17, 2016 9:37 PM
    Wednesday, August 17, 2016 9:19 PM
  • Thanks, Can we upload Linux machines in same patterns? Is there any place if i can download Linux machine sample and then try to upload it?

    Tariq Younas

    Thursday, August 18, 2016 1:13 AM
  • Hi Tariq, 

    Depends on OS Distribution, you should take a look at: https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-linux-classic-create-upload-vhd/

    Remember when creating the image you should add:

    --os Linux



    David Rendón @DaveRndn

    Thursday, August 18, 2016 4:29 AM
  • Thanks,

    can we make these uploaded VM part of VNet? OR do we need to deploy VM using ARM?

    Do we need above script version in ARM in order to achieve this?


    Tariq Younas

    Thursday, August 18, 2016 5:00 AM
  • Hi Tariq, 

    It´s recommended to add the VM´s into a Vnet/Subnet, you could try to deploy this very simple deployment of a Linux VM

    {
      "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "adminUsername": {
          "type": "string",
          "metadata": {
            "description": "User name for the Virtual Machine."
          }
        },
        "adminPassword": {
          "type": "securestring",
          "metadata": {
            "description": "Password for the Virtual Machine."
          }
        },
        "dnsLabelPrefix": {
          "type": "string",
          "metadata": {
            "description": "Unique DNS Name for the Public IP used to access the Virtual Machine."
          }
        },
        "ubuntuOSVersion": {
          "type": "string",
          "defaultValue": "14.04.2-LTS",
          "allowedValues": [
            "12.04.5-LTS",
            "14.04.2-LTS",
            "15.10",
            "16.04.0-LTS"
          ],
          "metadata": {
            "description": "The Ubuntu version for the VM. This will pick a fully patched image of this given Ubuntu version. Allowed values: 12.04.5-LTS, 14.04.2-LTS, 15.10, 16.04.0-LTS."
          }
        }
      },
      "variables": {
        "storageAccountName": "[concat(uniquestring(resourceGroup().id), 'salinuxvm')]",
        "dataDisk1VhdName": "datadisk1",
        "imagePublisher": "Canonical",
        "imageOffer": "UbuntuServer",
        "OSDiskName": "osdiskforlinuxsimple",
        "nicName": "myVMNic",
        "addressPrefix": "10.0.0.0/16",
        "subnetName": "Subnet",
        "subnetPrefix": "10.0.0.0/24",
        "storageAccountType": "Standard_LRS",
        "publicIPAddressName": "myPublicIP",
        "publicIPAddressType": "Dynamic",
        "vmStorageAccountContainerName": "vhds",
        "vmName": "MyUbuntuVM",
        "vmSize": "Standard_D1",
        "virtualNetworkName": "MyVNET",
        "vnetID": "[resourceId('Microsoft.Network/virtualNetworks',variables('virtualNetworkName'))]",
        "subnetRef": "[concat(variables('vnetID'),'/subnets/',variables('subnetName'))]",
        "apiVersion": "2015-06-15"
      },
      "resources": [
        {
          "type": "Microsoft.Storage/storageAccounts",
          "name": "[variables('storageAccountName')]",
          "apiVersion": "2016-01-01",
          "location": "[resourceGroup().location]",
          "sku": {
            "name": "[variables('storageAccountType')]"
          },
          "kind": "Storage",
          "properties": {}
        },
        {
          "apiVersion": "[variables('apiVersion')]",
          "type": "Microsoft.Network/publicIPAddresses",
          "name": "[variables('publicIPAddressName')]",
          "location": "[resourceGroup().location]",
          "properties": {
            "publicIPAllocationMethod": "[variables('publicIPAddressType')]",
            "dnsSettings": {
              "domainNameLabel": "[parameters('dnsLabelPrefix')]"
            }
          }
        },
        {
          "apiVersion": "[variables('apiVersion')]",
          "type": "Microsoft.Network/virtualNetworks",
          "name": "[variables('virtualNetworkName')]",
          "location": "[resourceGroup().location]",
          "properties": {
            "addressSpace": {
              "addressPrefixes": [
                "[variables('addressPrefix')]"
              ]
            },
            "subnets": [
              {
                "name": "[variables('subnetName')]",
                "properties": {
                  "addressPrefix": "[variables('subnetPrefix')]"
                }
              }
            ]
          }
        },
        {
          "apiVersion": "[variables('apiVersion')]",
          "type": "Microsoft.Network/networkInterfaces",
          "name": "[variables('nicName')]",
          "location": "[resourceGroup().location]",
          "dependsOn": [
            "[concat('Microsoft.Network/publicIPAddresses/', variables('publicIPAddressName'))]",
            "[concat('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]"
          ],
          "properties": {
            "ipConfigurations": [
              {
                "name": "ipconfig1",
                "properties": {
                  "privateIPAllocationMethod": "Dynamic",
                  "publicIPAddress": {
                    "id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"
                  },
                  "subnet": {
                    "id": "[variables('subnetRef')]"
                  }
                }
              }
            ]
          }
        },
        {
          "apiVersion": "[variables('apiVersion')]",
          "type": "Microsoft.Compute/virtualMachines",
          "name": "[variables('vmName')]",
          "location": "[resourceGroup().location]",
          "dependsOn": [
            "[concat('Microsoft.Storage/storageAccounts/', variables('storageAccountName'))]",
            "[concat('Microsoft.Network/networkInterfaces/', variables('nicName'))]"
          ],
          "properties": {
            "hardwareProfile": {
              "vmSize": "[variables('vmSize')]"
            },
            "osProfile": {
              "computerName": "[variables('vmName')]",
              "adminUsername": "[parameters('adminUsername')]",
              "adminPassword": "[parameters('adminPassword')]"
            },
            "storageProfile": {
              "imageReference": {
                "publisher": "[variables('imagePublisher')]",
                "offer": "[variables('imageOffer')]",
                "sku": "[parameters('ubuntuOSVersion')]",
                "version": "latest"
              },
              "osDisk": {
                "name": "osdisk",
                "vhd": {
                  "uri": "[concat(reference(concat('Microsoft.Storage/storageAccounts/', variables('storageAccountName')), variables('apiVersion')).primaryEndpoints.blob, variables('vmStorageAccountContainerName'),'/',variables('OSDiskName'),'.vhd')]"
                },
                "caching": "ReadWrite",
                "createOption": "FromImage"
              },
              "dataDisks": [
                {
                  "name": "datadisk1",
                  "diskSizeGB": "100",
                  "lun": 0,
                  "vhd": {
                    "uri": "[concat(reference(concat('Microsoft.Storage/storageAccounts/', variables('storageAccountName')), variables('apiVersion')).primaryEndpoints.blob, variables('vmStorageAccountContainerName'),'/',variables('dataDisk1VhdName'),'.vhd')]"
                  },
                  "createOption": "Empty"
                }
              ]
            },
            "networkProfile": {
              "networkInterfaces": [
                {
                  "id": "[resourceId('Microsoft.Network/networkInterfaces',variables('nicName'))]"
                }
              ]
            },
            "diagnosticsProfile": {
              "bootDiagnostics": {
                "enabled": "true",
                "storageUri": "[concat(reference(concat('Microsoft.Storage/storageAccounts/', variables('storageAccountName')), variables('apiVersion')).primaryEndpoints.blob)]"
              }
            }
          }
        }
      ],
      "outputs": {
        "hostname": {
          "type": "string",
          "value": "[concat(parameters('dnsLabelPrefix'), '.', resourceGroup().location, '.cloudapp.azure.com')]"
        },
        "sshCommand": {
          "type": "string",
          "value": "[concat('ssh ', parameters('adminUsername'), '@', parameters('dnsLabelPrefix'), '.', resourceGroup().location, '.cloudapp.azure.com')]"
        }
      }
    }

    Perhaps you could try some quickstart templates as well: 

    Linux VM with multiple NICs

     

    David Rendón @DaveRndn

    Thursday, August 18, 2016 2:01 PM
  • Hi David,

    Do you have ARM version of this script

    *********
    # Variables
    #*********************
    $Subscription = "[Your Subscription]"
    $SubscriptionId = "[Your SubscriptionId xxxx-xxxx-xxx]"
    $StorageAccountName = '[yourstorageaccountname]'
    $Location = 'East Us'
    $ContainerName = "[yourcontainername]"
    $LocalVHD = "C:\Users\Dave\Dropbox\KEMP\VLM-trial\LoadMasterVLM.vhd"
    $AzureVHD = "https://yourstorageaccountname.blob.core.windows.net/yourcontainername/LoadMasterVLM.vhd"
    $DiskName = 'LoadMaster-Hyper-V'
    $LabelName = 'LoadMaster-Hyper-V'
    $VMImageName = "LoadMaster"
    # *************************************
    # Prepare the access to your subscription
    #**************************************
    #Login to Azure Subscription
    Add-AzureAccount
    # List Available Windows Azure subscriptions
    Get-AzureSubscription | Format-Table -Property SubscriptionName
    #Set default Windows Azure subscription 
    Select-AzureSubscription -SubscriptionId $SubscriptionId -Default
    # Create a new storage account.
    New-AzureStorageAccount –StorageAccountName $StorageAccountName -Location $Location
    # Set a default storage account.
    Set-AzureSubscription -CurrentStorageAccountName $StorageAccountName -SubscriptionName $Subscription
    # Create a new container.
    New-AzureStorageContainer -Name $ContainerName -Permission Off
    # Get default Windows Azure Storage Account.
    Get-AzureStorageAccount | Format-Table -Property Label
    # Identify where the VHD is coming from and where it's going.
    Add-AzureVhd -LocalFilePath $LocalVHD -Destination $AzureVHD
    #Add the VHD to the “My Disk” section of the Gallery
    # Register as an OS disk 
    Add-AzureDisk -DiskName $DiskName -MediaLocation $AzureVHD -Label $LabelName -OS Windows
    #If you want to create the image
    Add-AzureVMImage -ImageName $VMImageName -MediaLocation $AzureVHD -OS Windows


    Tariq Younas

    Thursday, August 18, 2016 10:06 PM
  • Hi Tariq,

    After some testing, you could try this script, tried to make it as simple as possible, in this example you could deploy a single VM vía Resource Manager, adding some vnet/subnet configuration, public IP Address, NIC, 

    Consider to use the cmdlet: Login-AzureRmAccount and Select-AzureRmSubscription before running the script

    You can modify it to your own vhd purposes:

    #************************
    # Deploy VM via ARM
    # Author:@DaveRndn
    # http://wikiazure.com
    #***********************
    
    
    $Location = "West US"
    $ResourceGroupName = "TestDeployARM"
    $SubnetName = "Subnet-1"
    $TestName = "testdeployarm1"
    $VnetName = "VnetTestDeployARM"
    $Publisher = "MicrosoftWindowsServer"
    $Offer = "WindowsServer"
    $Sku = "2012-R2-Datacenter"
    $Version = "latest"
    
    
    New-AzureRmResourceGroup -Name $ResourceGroupName -Location $Location
    
    New-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $TestName -Location $Location -Type Standard_LRS
    
    $Subnet = New-AzureRmVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix "10.0.64.0/24"
    
    $Vnet = New-AzureRmVirtualNetwork -Name $VnetName -ResourceGroupName $ResourceGroupName -Location $Location -AddressPrefix "10.0.0.0/16" -Subnet $Subnet
    
    $Subnet = Get-AzureRmVirtualNetworkSubnetConfig -Name $SubnetName -VirtualNetwork $Vnet
    
    
    $PublicIpAdress = New-AzureRmPublicIpAddress -ResourceGroupName $ResourceGroupName -Name "VipTstARM" -Location $Location -AllocationMethod Dynamic -DomainNameLabel $TestName
    
    $Nic = New-AzureRmNetworkInterface -ResourceGroupName $ResourceGroupName -Name "Nic1tst" -Subnet $Subnet -Location $Location -PublicIpAddress $PublicIpAdress -PrivateIpAddress "10.0.64.4"
    
    $Cred = Get-Credential
    
    $VmConfig = New-AzureRmVMConfig -VMName "VM1" -VMSize "Standard_A1"  | 
                Set-AzureRmVMOperatingSystem -Windows -ComputerName "VM1" -Credential $Cred -ProvisionVMAgent -EnableAutoUpdate |
                Set-AzureRmVMSourceImage -PublisherName $Publisher -Offer $Offer -Skus $Sku -Version $Version |
                Set-AzureRmVMOSDisk -Name "$TestName-v1" -VhdUri "https://testdeployarm1.blob.core.windows.net/vhd/$TestName-v1.vhd" -Caching ReadWrite -CreateOption fromImage |
                Add-AzureRmVMNetworkInterface -Id $Nic.Id
    
    New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $Location -VM $VmConfig

    Best regards!


    Dave Rendón @DaveRndn



    Tuesday, August 23, 2016 11:06 PM
  • Thanks David. In above script where we are uploading VHD from local to Azure?

    Tariq Younas

    Tuesday, August 23, 2016 11:45 PM
  • Hi Tariq, 

    Not sure if there was a merge in last comments... 

    about the storage, you could check if the blob already exists: 

    try
    {   
        $blob = Get-AzureStorageBlob -Blob $azureBlobName -Container $azureStorageContainer -Context $azureContext -ErrorAction Stop
    }
    catch [Microsoft.WindowsAzure.Commands.Storage.Common.ResourceNotFoundException]
    {
        # Add logic here to remember that the blob doesn't exist...
        Write-Host "Blob Not Found"
    }
    catch
    {
        # Report any other error
        Write-Error $Error[0].Exception;
    }

    An easier way to check try the http://storageexplorer.com/

    The best way is to migrate it vía ASM with the 1st script and then deploy the VM using 2nd, 

    $VMConfig = Set-AzureRmVMOperatingSystem -VM $VirtualMachine -Windows -ComputerName $ComputerName -Credential $Cred -ProvisionVMAgent -EnableAutoUpdate
    $VMConfig = Set-AzureRmVMSourceImage -VM $VirtualMachine

    Perhaps this examples might also help: https://msdn.microsoft.com/en-us/library/mt603754.aspx


    David Rendón @DaveRndn

    • Marked as answer by Tariq Younas Wednesday, August 24, 2016 1:54 AM
    Tuesday, August 23, 2016 11:53 PM
  • Thank you David.
    Wednesday, August 24, 2016 9:57 PM