How to create a virtual machine from a VHD using PowerShell

Source: Internet
Author: User
Tags documentation

Sharing an azure-related blog is also about creating virtual machines, which is the most common task in azure.

Many times when we are migrating from on-premises to Azure or migrating from one azure tenant to another, we encounter the problem of how to migrate a virtual machine or a physical machine, which is generally the simplest way to migrate a VHD, and Azure itself is built on top of hyper-V, If you have previously used azure or a generation of hyper-V virtual machines, it is not technically too complicated to migrate without considering whether the business is allowed to break.


First, if it is a local virtual machine or physical machine, after the conversion of the VHD file needs to be uploaded to the Azure Storage account, in order to create a virtual machine, upload a lot of methods, generally recommended is the use of Azcopy, this is Microsoft's own tool, Scenarios that can support many file copies, including migrating data from different storage account, Azure file migration data, and more, refer to Microsoft's official documentation for a more detailed introduction to Azcopy https://docs.microsoft.com/ Zh-cn/azure/storage/common/storage-use-azcopy


The document is Azure Global, but the tool itself supports mooncake, and if you want to download azcopy, you can download it directly from this short address http://aka.ms/downloadazcopy


Azcopy's use of the method is not introduced, not complicated, Microsoft's documentation is also written in detail. Below is how to create a virtual machine after uploading a VHD to an azure Storage account, it is well known that ARM does not have the ability to create virtual machines directly from the portal using a VHD like ASM, which needs to be done with PowerShell under arm. A lot of similar scripts, but generally made more flexible parameterization of the less, all need to modify a lot of variables, today to share a script I use


     first code, this script is actually the same as what I shared before, can support Mooncake and azure Global, if mooncake need to use switch Azuremooncake control, the script itself needs to specify a lot of parameters, because when creating a virtual machine to use a lot of parameters, such as Vnet,subnet,resourcegroup, and so on, some parameters must be specified, such as the URI of the VHD, the name of the virtual machine , subnet and vnet name, to note that this script if resourcegroup,subnet or vnet does not exist will be automatically created, address space is vnetprefix, etc. to control, these are default values, if you want to use their own, Please specify in the parameters, the script automatically generated network card these function is actually a reference Script center in the scripts, coupled with their own according to the needs of a certain modification, here to special thanks to the next

PARAM ([Parameter (mandatory =  $false)][switch] $AzureMoonCake, [parameter (mandatory =  $false) ][switch] $DoNotLogin, [Parameter (mandatory =  $true)][string] $LocationName, [Parameter (mandatory =   $true)][string] $ResourceGroupName, [parameter (mandatory =  $true)][string] $VMName, [Parameter ( mandatory =  $true)][string] $VhdUri, [parameter (mandatory =  $true)][string] $VnetName, [ Parameter (mandatory =  $true)][string] $SubnetName, [parameter (mandatory =  $false)][switch]$ Hybridbenefit,[parameter (mandatory =  $false)][string] $VMSizeName  =  "Standard_d2", [ Parameter (mandatory =  $false)][string] $AvailabilitySetName, [parameter (mandatory =  $false)] [Validateset ("Windows",  "Linux")] [string] $OS  =  ' Windows ', [parameter (mandatory =  $false)][string] $VnetPrefix  =  " 10.140.0.0/16 ", [Parameter (mandatory =  $false)][string] $SubnetPrefix  = " 10.140.0.0/[Parameter (mandatory =  $false)][validateset ("Static",  "Dynamic")][string]$ publicipallocationmethod =  "Dynamic") #检查Location是否存在 and returns the result Function check-azurermlocation () { Param ([string] $LocationName  = $ (throw  "parameter missing: -locationname  LocationName ")) write-host " $ (get-date)  * Checking location  $LocationName " - Foregroundcolor green$location = get-azurermlocation | where-object { $_. location -eq  $LocationName  }If  (-not  ($Location)) {write-host  "$ (get-date)  *  the location "  $LocationName   does not exist."  -ForegroundColor Redreturn  $false}else{write-host  "$ (get-date)  * Location  $LocationName  exists " -ForegroundColor Greenreturn  $true}} #检查RG是否存在, does not exist create a new rgfunction  check-azurermresourcegroup () {param ([string] $ResourceGroupName  = $ (throw  "Parameter missing: -resourcegroupname resourcegroupname"), [string] $LocationName   = $ (throw  "Parameter missing: -locationname locationname")) Write-Host  "$ ( get-date)  * Checking resource group  $ResourceGroupName, if not,  Created it. "  -foregroundcolor greentry{$ResourceGroup  = get-azurermresourcegroup -name $ resourcegroupname -location  $LocationName  -ErrorAction SilentlyContinueIf  (-not  ($ResourceGroup)) {write-host  "$ (get-date)  * creating resource group"   $ResourceGroupName   "... " -ForegroundColor GreenNew-AzureRmResourceGroup -Name  $ResourceGroupName  -location   $LocationName  -ErrorAction Stopreturn  $true}else{write-host  "$ (get-date)  *  Resource group  $ResourceGroupName  exists " -ForegroundColor Greenreturn  $true}}catch{write-host -foregroundcolor red  "$ (get-date)  * Create resource  Group "  $LocationName  " failed. "  $_. exception.messagereturn  $false}} #随机生成新的NICfunction  autogenerate-azurermnetworkinterface () {param ([ String] $ResourceGroupName  = $ (throw  "parameter missing: -resourcegroupname  Resourcegroupname "), [string] $LocationName  = $ (throw " Parameter missing: -locationname  locationname "), [string] $VMName  = $ (throw " parameter missing: -vmname  VMName "), [string] $SubnetName, [string] $VnetName, [string] $SubnetPrefix  = " 10.140.0.0/24 ", [string]$ vnetprefix =  "10.140.0.0/16", [switch] $Create, [string] $PublicIPAllocationMethod  =  "Dynamic" ) try{$RandomNum  = get-random -minimum 100 -maximum 9999$ipname = $ vmname +  "-ip"  +  $RandomNum $nicname =  $VMName  +  "-ni"  +  $RandomNumWrite-host  "$ (get-date)  * auto generate network interface   $NicName " -foregroundcolor green$pip = new-azurermpublicipaddress -name $ ipname -resourcegroupname  $ResourceGroupName  -Location  $LocationName  - allocationmethod  $PublicIPAllocationMethod  -ErrorAction Stopif  ($Create) {#Vnet  does  not exist$Subnet = New-AzureRmVirtualNetworkSubnetConfig -Name  $SubnetName  -AddressPrefix  $SubnetPrefix  -erroraction stop$vnet = new-azurermvirtualnetwork  -Name  $VnetName  -ResourceGroupName  $ResourceGroupName  -Location  $LocationName  -AddressPrefix  $VnetPrefix  -Subnet  $Subnet  -ErrorAction Stop$Nic =  new-azurermnetworkinterface -name  $NicName  -ResourceGroupName  $ResourceGroupName  - location  $LocationName  -subnetid  $Vnet. subnets[0]. id -publicipaddressid  $Pip. id -erroraction stop}else{#Vnet  exist$Vnet =  get-azurermvirtualnetwork -resourcegroupname  $ResourceGroupName  -Name  $VnetName  - erroraction stop$subnet = get-azurermvirtualnetworksubnetconfig -virtualnetwork  $Vnet  -Name  $SubnetName  -ErrorAction SilentlyContinueif  ($subnet  -eq  $null) {# subnet does not existwrite-host  "$ (get-date)  * Subnet  $SubnetName  does  not exist,create it,subnet prefix  $SubnetPrefix " -foregroundcolor green$ subnet = new-azurermvirtualnetworksubnetconfig -name  $SubnetName  -AddressPrefix  $SubnetPrefix  -ErrorAction Stop$vnet.subnets +=  $Subnet #update  vnetset-azurermvirtualnetwork -virtualnetwork  $Vnet  -ErrorAction Stop#get vnet  Again$vnet =&nbsP get-azurermvirtualnetwork -resourcegroupname  $ResourceGroupName  -Name  $VnetName  - erroraction stop$subnet = get-azurermvirtualnetworksubnetconfig -name  $SubnetName  -VirtualNetwork  $Vnet  -ErrorAction stop$Nic = New-AzureRmNetworkInterface  -name  $NicName  -ResourceGroupName  $ResourceGroupName  -Location  $LocationName  - subnetid  $Subnet .id -publicipaddressid  $Pip. id -erroraction stop}else{#subnet   existwrite-host  "$ (get-date)  * Subnet  $SubnetName  exist"  -ForegroundColor  green$nic = new-azurermnetworkinterface -name  $NicName  -resourcegroupname $ resourcegroupname -location  $LocationName  -SubnetId  $Subnet. Id -publicipaddressid   $Pip .id -erroraction stop}}return  $Nic. id}catch{write-host -foregroundcolor red   "$ (get-date)  *  Auto generate network interface " $_. exception.messagereturn  $false}} #Login  Azure with ARM modeImport-Module  Azurerm.profile$error.clear () if  (! $DoNotLogin) {if  ($AzureMoonCake) {write-warning  "$ (get-date)  * current environment is azure china (mooncake) "Login-AzureRmAccount - environmentname azurechinacloud}else{write-warning  "$ (get-date)  * current environment  is azure global "login-azurermaccount}if  ($? -eq  $true) {Write-Host " $ ( Get-date)  * login succeeded! "  -ForegroundColor Green}else{Write-Host  $Error [0]. exception.message -foregroundcolor redbreak}}else{$CurrentSubscription  =  get-azurermsubscriptionif  ($CurrentSubscription  -eq  $null) {write-warning  "$ (get-date)  * didn ' T find any subscription for now! please login ' Break}}try{#check  location$error.clear () if  (check-azurermlocation -locationname  $LocationName) {# check rm resource group, if not exist, create oneif  ( check-azurermresourcegroup -resourcegroupname  $ResourceGroupName  -locationname $ LocationName) {#Check  VM NameIf  (get-azurermvm -name  $VMName  -resourcegroupname   $ResourceGroupName  -erroraction ignore) {write-host -foregroundcolor red  "$ ( get-date)  * VM  $VMName  has already exist. "} else{#Check  VM SizeWrite-Host  "$ (get-date)  * checking vm size $ Vmsizename " -ForegroundColor GreenIf  (get-azurermvmsize -location  $LocationName   | where-object { $_. name -eq  $VMSizeName  }) {write-host  "$ (get-date)  * VM Size  $VMSizeName  exist "&NBSP;-FOREGROUNDCOLOR&NBSP;GREENIF&NBSP; ($VhdUri) {#Create  a network interface$vnet = get-azurermvirtualnetwork - resourcegroupname  $ResourceGroupName  -Name  $VnetName  -erroraction silentlycontinueif   ($Vnet  -eq  $null) {write-host  "$ (get-date)  * Virtual network  $VnetName  does not exist,create it,vnet prefix  $VnetPrefix " -ForegroundColor  green$nid = autogenerate-azurermnetworkinterface -location  $LocationName  - resourcegroupname  $ResourceGroupName  -VMName  $VMName  -VnetName  $VnetName  - vnetprefix  $VnetPrefix  -SubnetName  $SubnetName  -SubnetPrefix  $SubnetPrefix  - publicipallocationmethod  $PublicIPAllocationMethod  -Create}else{Write-Host  "$ (get-date)  *  Virtual network  $VnetName  exist " -ForegroundColor Green$Nid =  Autogenerate-azurermnetworkinterface -location  $LocationName  -ResourceGroupName  $ResourceGroupName  -VMName  $VMName  - vnetname  $VnetName  -VnetPrefix  $VnetPrefix  -SubnetName  $SubnetName  -subnetprefix   $SubnetPrefix  -PublicIPAllocationMethod  $PublicIPAllocationMethod}if  ($Nid) {Write-host   "$ (get-date)  * Creating VM  $VMName   ..."  -foregroundcolor greenif   ($AvailabilitySetName) {write-host  "$ (get-date)  * verify availability set"   -foregroundcolor green$availabilityset = get-azurermavailabilityset -resourcegroupname   $ResourceGroupName  -Name  $AvailabilitySetName  -ErrorAction SilentlyContinueif  ( ! $AvailabilitySet) {write-host  "$ (get-date)  * AvailabilitySet  $AvailabilitySetName   Does not exist, create a new one " -foregroundcolor green$ Availabilityset = new-azurermavailabilityset -resourcegroupname  $ResourceGroupName  -Name  $AvailabilitySetName  - location  $LocationName  -erroraction stop$vm = new-azurermvmconfig -vmname $ vmname -vmsize  $VMSizeName  -AvailabilitySetId  $AvailabilitySet .id -erroraction  stop}else{$VM  = New-AzureRmVMConfig -VMName  $VMName  -VMSize  $VMSizeName  - availabilitysetid  $AvailabilitySet. id -erroraction stop}}else{$VM  =  new-azurermvmconfig -vmname  $VMName  -VMSize  $VMSizeName  -erroraction stop}}# choose source image# $VM  = Set-AzureRmVMSourceImage -VM  $VM  -publishername   $PublisherName  -Offer  $OfferName  -Skus  $SkusName  -Version  "latest"  - Erroraction stop#add the network interface to the configuration. $VM  =  add-azurermvmnetworkinterface -vm&nbsp, $VM  -Id  $Nid  -ErrorAction Stop$DiskName =  "Vmosdisk" # $vmConfig  =  set-azurermvmosdisk -vm  $vmConfig  -Name  $osDiskName  -VhdUri  $DESTINATIONVHD  -createoption attach -linux# $VM  = Set-AzureRmVMOSDisk -VM  $VM  -name   $DiskName  -VhdUri  $OSDiskUri  -createoption fromimage -caching $ osdiskcaching -erroraction stopif  ($OS  -eq  "Windows") {$VM  =  set-azurermvmosdisk -vm  $VM  -Name  $DiskName  -VhdUri  $VhdUri  -createoption  attach -caching none -windows -erroraction stop}else{$VM  =  set-azurermvmosdisk -vm  $VM  -Name  $DiskName  -VhdUri  $VhdUri  -createoption  attach -caching none -linux -erroraction stop} #Create  a virtual  machineif  ($HybridBenefit) {write-host  "$ (get-daTE)  * Hybrid Benefit enabled for VM  $VMName  ! "  -ForegroundColor GreenNew-AzureRmVM -ResourceGroupName  $ResourceGroupName  -location   $LocationName  -VM  $VM  -ErrorAction Stop -LicenseType  "Windows_server"  | Out-Null}else{New-AzureRmVM -ResourceGroupName  $ResourceGroupName  -location $ locationname -vm  $VM  -ErrorAction Stop | Out-Null}Write-Host  "$ (get-date)  * Create virtual machine  $VMName  successfully! "  -ForegroundColor Green#Set private nic to static< #start-sleep 5$nicname  =  $NID Split ("/") [-1] $Nic  = Get-AzureRmNetworkInterface -Name  $NicName  - resourcegroupname  $ResourceGroupName $nic.ipconfigurations[0]. privateipallocationmethod =  "Static" set-azurermnetworkinterface -networkinterface  $Nic  | out-null#>}}else{write-host -foregroundcolor red  "$ (get-date)  * vm size $ Vmsizename does not exist. "}}}} catch{write-host -foregroundcolor red  "$ (get-date)  * Create a virtual  machine  $VMName  failed " $_. Exception.Message}



The script itself lazy did not write too complex help information, so it may not be very good to start how to run, the following is the most basic example, before the script to the limitations of the word

itself this script can support the creation of ARM virtual machines, including premium storage or ordinary HDD, but before creating premium storage virtual machines, make sure that your VHD files are also placed in the Preimum Storage account, otherwise the creation of the time will certainly be error. In addition, this script only supports the unmanaged disk, the managed disk is not engaged for a while, ready to get out and then update the script


Vnetname These parameters are basically no longer introduced, are very well understood, hybridbenefit to specifically, because now is a local Windows Server can be directly used license to Azure virtual machines (of course, this is a prerequisite, not much to talk about) , in which case you need to specify Hybridbenefit when creating the virtual machine, and the script has a hybridbenefit switch to let the user specify whether to create a mixed-benefit VM


Below is the simplest example of creating a Windows virtual machine, you need to run the script to specify the parameters below, because it is the Chinese version, so add Azuremooncake, because you have already logged in so you want to add-donotlogin, otherwise you will have to log in again, The basic is no need to say more, the meaning is very clear

PS c:\users\mxy> D:\Create-AzureRMVMFromImageV4.ps1-AzureMoonCake-DoNotLogin-LocationName Chinanorth- Resourcegroupname ps_resourcemg-vmname Ttt-vhduri Https://mxymigration.blob.core.chi

Nacloudapi.cn/vhds/azuretest.vhd-vnetname mxyansible-subnetname Subnet1-hybridbenefit-vmsizename Standard_d2-os Windows-publicipallocationmethod Static


This is the run time.



Note that when using a locally uploaded VHD creation, it is very likely that the script will not be able to perform the completion of the card, the last create VM can be stuck in the end, you may get such an error


This is not really nervous, in fact, the virtual machine has been created, but because the local VM is not installed by default VM agent, the system can not detect when the problem occurs, the virtual machine is not a problem, if you want to avoid this problem, you can advance the VM agent locally installed, the rear VM Agent


Basically, in different scenarios, the properties of the virtual machine can be controlled by different parameters.

How to create a virtual machine from a VHD using PowerShell

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.