Finding the most recent Windows Server 2012 R2 template with PowerShell

I'm often creating new VM instances with PowerShell.   I always like to use the most recently published template from the Azure marketplace when creating it.   If you've ever ran the Get-AzureVMImage powershell cmdlet you'll be overwhelmed with hundreds of choices.   This is a quick one-liner to find the most recently published template in the Windows Server 2012 R2 Datacenter family.

 

#One liner to get the image name

 $imageName = (Get-AzureVMImage | WHERE {$_.ImageFamily -like "Windows Server 2012 R2 Datacenter"} | Sort-Object PublishedDate -Descending | Select -First 1 ImageName).ImageName

 

#Create a VM instance based on it

  $subscriptionName = "subscription"
 $storageAccount = "accountname"
 $adminName = "admin"
 $adminPassword = "password"
 $vmName ="yourVM"
 $location = "West US"
 $vmSize ="Standard_D2"
 $OSDiskPath = "https://" + $storageAccount + ".blob.core.windows.net/vhds/" + $vmName + "_OS.vhd"
 Set-AzureSubscription -SubscriptionName $subscriptionName -CurrentStorageAccountName $storageAccount
 $vm = New-AzureVMConfig -Name $vmName -ImageName $imageName -InstanceSize $vmSize -MediaLocation $OSDiskPath
 Add-AzureProvisioningConfig -Windows -VM $vm -AdminUsername $adminName -Password $adminPassword
 New-AzureVM -ServiceName $vmName -VMs $VM -Location $location

Comments

  • Anonymous
    April 01, 2015
    This looks awesome!, but as just a quick follow up it'd be nice if us PS users started trying to watch line count and readability. Here is the same code with some clean up.$subscriptionName = "subscription"$storageAccount     = "accountname"$adminName           = "admin"$adminPassword     = "password"$vmName                = "yourVM"$location                  = "West US"$vmSize                   = "Standard_D2"$osselection             = "Windows Server 2012 R2 Datacenter"$imageName =   (Get-AzureVMImage | WHERE    { $_.ImageFamily -like $osselection } |   Sort-Object PublishedDate -Descending |   Select -First 1 ImageName   ).ImageName$OSDiskPath =    ("https://" + $storageAccount +    ".blob.core.windows.net/vhds/" +    $vmName + "_OS.vhd")   Set-AzureSubscription            -SubscriptionName $subscriptionName            -CurrentStorageAccountName $storageAccount$vm = New-AzureVMConfig            -Name $vmName            -ImageName $imageName            -InstanceSize $vmSize            -MediaLocation $OSDiskPath   Add-AzureProvisioningConfig            -Windows            -VM $vm            -AdminUsername $adminName            -Password $adminPassword   New-AzureVM            -ServiceName $vmName            -VMs $VM `           -Location $location
  • Anonymous
    August 18, 2016
    Hi How can we get $imageName in Resource Manager. I need to deploy multiple VMs which will be using Premium Disk hence i am planning to use powershell. Thanks