Retrieve the latest version of a Gallery Image in Azure PowerShell

Here is a handy snippet I use fairly often. When you retrieve an Azure gallery image by name, you will find there are multiple versions of the image.

Get-AzureVMImage -Verbose:$false | Where-Object {$_.label -like “Windows Server 2012 Datacenter*”} | Select-Object Label, PublishedDate

You will typically find at least two versions of each image, which can be differentiated by date, as shown below.

Label       PublishedDate
—–         ————-
Windows Server 2012 Datacenter, February 2015 2/11/2015 2:00:00 AM
Windows Server 2012 Datacenter, March 2015 3/12/2015 2:00:00 AM

Finding the latest image is as simple as retrieving all of them and sorting in descending order based on the published date. The code below will arrange the images in descending order by published date, then retrieve the first in the list.

(Get-AzureVMImage -Verbose:$false | Where-Object {$_.label -like “Windows Server 2012 Datacenter*”}| Sort-Object –Descending PublishedDate)[0].ImageName

We can save this result to a variable and proceed with deployment.

$winImageName = (Get-AzureVMImage | where {$_.label –like “Windows Server 2012 Datacenter*”} | sort PublishedDate -Descending)[0].ImageName

I’ll follow this post with a many more in this vein, offering some tips to optimize your Azure scripting.

Leave a Reply