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
}
}
CodePudding user response:
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: