Azure:获取Azure自动化的资源

y0u0uwnf  于 2022-11-17  发布在  其他
关注(0)|答案(1)|浏览(163)

我在Azure中有要在不同RG中使用Runbook,
我的代码

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

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

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

如何更新代码,使脚本获得它所在的RG的名称,
这样RG就不会被硬编码
不知道怎么做

2exbekwf

2exbekwf1#

做类似这样的事情

$rgs = $(Get-AzVM)
# Get Distinct RG Names
$rgs = $rgs | Select-Object -Property ResourceGroupName | Sort-Object -Unique
foreach($rg in $rgs){
  $vms = Get-AzVM -ResourceGroupName $rg.ResourceGroupName
    foreach($vm in $vms)
    {
    $statuscheck = Get-AzVM -ResourceGroupName $rg.ResourceGroupName -Name $vm.Name -Status 
        if($statuscheck.Statuses.DisplayStatus[1] -eq "VM running")
        {  

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

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

相关问题