简体   繁体   English

Powershell 脚本获取正在运行的虚拟机列表并停止它们

[英]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我正在使用这个脚本,但它收集所有的虚拟机并一一停止它,即使虚拟机已经停止 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.基于上述共享需求,我们修改了 PowerShell 脚本来检查虚拟机状态(是否正在运行),如果虚拟机正在运行,您需要使用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.在我们的本地环境中检查了以下脚本(在测试时我们将资源组标志传递给Get-Azvm ),它工作正常。

$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:以下是样品 output 供参考:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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