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