简体   繁体   中英

Powershell script to get list of Running VM's and stop them

Am using this script, but its gathering all the vms and stopping it one by one even when the VM is already in stopped state

$vm = Get-Azvm 

foreach($vms in $vm)

{
    
    $resource = Get-Azvm | where {$_.Statuses -eq "Running"}

    if($resource -ne $null)
    {  
        Write-Output "Stopping virtual machine..." + $vms
        Stop-AzVM -ResourceGroupName $resource.ResourceGroupName -Name $vms -Force
    }   
    else
    {
        Write-output "Virtual machine not found:" + $vms
    }
}

Based on the above shared requirement, we have modified the PowerShell script to check the virtual machines status ( whether it is running or not ), if virtual Machine is running you need to stop it using stop-Azvm cmdlet.

Checked the below script(while testing we passed resource group flag to the Get-Azvm ) in our local environment which is working fine.

$vm = Get-Azvm -Status

foreach($vms in $vm)
{
   $statuscheck = Get-AzVM -ResourceGroupName $vms.ResourceGroupName -Name $vms.Name -Status 
    if($statuscheck.Statuses.DisplayStatus[1] -eq "VM running")
    {  

        Write-Output "Stopping virtual machine...$($vms.Name)"

        Stop-AzVM -ResourceGroupName $vms.ResourceGroupName -Name $vms.Name -Force
    }   
    else
    {
        Write-output "Virtual machine $($vms.Name) is already in stopped state"
    }
}

Here is the sample output for reference:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM