azure 如何通过定义资源组变量自动获取VM详细信息

k0pti3hp  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(186)

我正在准备PowerShell脚本来禁用自动-多个资源组中所有Azure VM的关闭选项。到目前为止,我已经准备好脚本,通过将资源组名称和VM名称定义为变量,为单个资源组和单个VM禁用自动关闭选项。但我只需要将资源组名称定义为变量,并且我需要从该资源组变量获取VM详细信息。可以使用请帮我解决这个问题。
下面是PowerShell脚本:

# Sign in to your Azure account
Connect-AzAccount

    # Define an array of resource group names
    $resourcegroups = @("RG-Test1",  "RG-Test2")
    
    # Define an array of VM names
    $vms = @("devvm1", "DevVm2")
    
    $shutdown_time = "0000"
    $shutdown_timezone = "India Standard Time"
    
    # Loop through resource groups and VMs
    for ($i = 0; $i -lt $resourcegroups.Length; $i++) {
        $resourcegroup = $resourcegroups[$i]
        $vm = $vms[$i]
    
        $properties = @{
            "status" = "Disabled"
            "taskType" = "ComputeVmShutdownTask"
            "dailyRecurrence" = @{"time" = $shutdown_time }
            "timeZoneId" = $shutdown_timezone
            "notificationSettings" = @{
                "status" = "Disabled"
                "timeInMinutes" = 00
            }
            "targetResourceId" = (Get-AzVM -ResourceGroupName $resourcegroup -Name $vm).Id
        }
    
        New-AzResource -ResourceId ("/subscriptions/{0}/resourceGroups/{1}/providers/microsoft.devtestlab/schedules/shutdown-computevm-{2}" -f (Get-AzContext).Subscription.Id, $resourcegroup, $vm) -Location (Get-AzVM -ResourceGroupName $resourcegroup -Name $vm).Location -Properties $properties -Force
    }

字符串

uhry853o

uhry853o1#

您可以使用下面的脚本只定义资源组名称作为变量,并从该资源组获取VM详细信息。

# Define an array of resource group names
$resourcegroups = @("RG1", "RG2")

$shutdown_time = "0000"
$shutdown_timezone = "India Standard Time"

# Loop through resource groups
foreach ($resourcegroup in $resourcegroups) {
    $vmsInResourceGroup = Get-AzVM -ResourceGroupName $resourcegroup
    
    foreach ($vm in $vmsInResourceGroup) {
        $properties = @{
            "status" = "Disabled"
            "taskType" = "ComputeVmShutdownTask"
            "dailyRecurrence" = @{"time" = $shutdown_time }
            "timeZoneId" = $shutdown_timezone
            "notificationSettings" = @{
                "status" = "Disabled"
                "timeInMinutes" = 00
            }
            "targetResourceId" = $vm.Id
        }
        
        $scheduleName = "shutdown-computevm-" + $vm.Name

        New-AzResource -ResourceId ("/subscriptions/{0}/resourceGroups/{1}/providers/microsoft.devtestlab/schedules/$scheduleName" -f (Get-AzContext).Subscription.Id, $resourcegroup) -Location $vm.Location -Properties $properties -Force
    }
}

字符串
现在您可以获取VM详细信息并禁用多个资源组中所有Azure VM的自动关闭选项。如下所示:

  • 输出 *:


的数据

相关问题