Checking Azure VM Existence with PowerShell

In this blog post, we will discuss how to check if an Azure VM exists using PowerShell.

If you are working with Azure Virtual Machines, it is essential to know how to check if a VM exists or not using PowerShell.

Once you have installed Azure PowerShell, open PowerShell and connect to your Azure account using the following command:

Connect-AzAccount

Next, set the name of the VM you want to check using the following command:

$vmName = "ntadminvm"

In this example, we have set the name of the VM to “ntadminvm”. Replace this with the name of your VM.

Now, we will use the Get-AzVM command to check if the VM exists. The following code will check if the VM exists and store the VM object in the $vm variable:

$vm = Get-AzVM -Name $vmName -ErrorAction SilentlyContinue

The ErrorAction parameter is set to SilentlyContinue, which means if the VM does not exist, the command will not throw an error. Instead, it will return $null.

Finally, we will check if the $vm variable is equal to $null. If it is, the VM does not exist. If it is not, the VM exists. The following code will display a message accordingly:

if ($vm -eq $null) {
    Write-Host "Virtual machine '$vmName' does not exist"
}
else {
    Write-Host "Virtual machine '$vmName' exists"
}

Now you know how to check if an Azure VM exists using PowerShell. Use this code snippet to automate your scripts and ensure that the VM you need is available before performing any operations on it.

Full Code

$vmName = "nnweeklyvm"
$vm = Get-AzVM -Name $vmName -ErrorAction SilentlyContinue

if ($vm -eq $null) {
    Write-Host "Virtual machine '$vmName' does not exist"
}
else {
    Write-Host "Virtual machine '$vmName' exists"
}

Processing…
Success! You're on the list.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.