How to find if an Azure VM exists via PowerShell

One task that can be help to optimize deployments in Azure is checking for the existence of a VM before you attempt to deploy. This can be particularly useful when you attempt to restart a failed deployment of multiple VMs. Because every VM in Azure resides within a cloud service, checking for a VM can be a bit more work than in an on-premises scenario with VMM and Hyper-V.

If you know the name of the service the VM should reside within your Azure subscription, the check is quick and easy.

if (!(Get-AzureVM -ServiceName "MyCloudService" -Name "MyVMName"))

On the other hand, sometimes you will not know which cloud service the VM resides in (as when generating random cloud service names in a bulk deployment). In this case, you will need to check every cloud service for the existence of the VM. The function below is one example of to determine if a VM exists within an Azure subscription if you do not know the name of the cloud service. The last line calls the function and provides the name of  a VM.

 Function Check-AllServices4VM ($vmName) {

 $cloudServices = Get-AzureService 

 ForEach ($Service in $cloudServices) {

 If (Get-AzureVM -ServiceName $Service.ServiceName -Name $vmName) {

 Write-Host "Azure VM by that name already exists in service " $Service.ServiceName " ...terminating"
 Break
      }
     Else
      {
    Write-Host "Azure VM does not exist is service " $Service.ServiceName
      }
   }
 } # end of function 

 # Call the function and provide VM name
 Check-AllServices4VM -vmName SQLClient

That’s all for today. Leave any thoughts in comments.

Print Friendly, PDF & Email
Posted in Blog Tagged with: ,

Leave a Reply

%d bloggers like this: