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

k0pti3hp  于 2023-11-21  发布在  其他
关注(0)|答案(1)|浏览(281)

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

  1. # Sign in to your Azure account
  2. Connect-AzAccount
  3. # Define an array of resource group names
  4. $resourcegroups = @("RG-Test1", "RG-Test2")
  5. # Define an array of VM names
  6. $vms = @("devvm1", "DevVm2")
  7. $shutdown_time = "0000"
  8. $shutdown_timezone = "India Standard Time"
  9. # Loop through resource groups and VMs
  10. for ($i = 0; $i -lt $resourcegroups.Length; $i++) {
  11. $resourcegroup = $resourcegroups[$i]
  12. $vm = $vms[$i]
  13. $properties = @{
  14. "status" = "Disabled"
  15. "taskType" = "ComputeVmShutdownTask"
  16. "dailyRecurrence" = @{"time" = $shutdown_time }
  17. "timeZoneId" = $shutdown_timezone
  18. "notificationSettings" = @{
  19. "status" = "Disabled"
  20. "timeInMinutes" = 00
  21. }
  22. "targetResourceId" = (Get-AzVM -ResourceGroupName $resourcegroup -Name $vm).Id
  23. }
  24. 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
  25. }

字符串

uhry853o

uhry853o1#

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

  1. # Define an array of resource group names
  2. $resourcegroups = @("RG1", "RG2")
  3. $shutdown_time = "0000"
  4. $shutdown_timezone = "India Standard Time"
  5. # Loop through resource groups
  6. foreach ($resourcegroup in $resourcegroups) {
  7. $vmsInResourceGroup = Get-AzVM -ResourceGroupName $resourcegroup
  8. foreach ($vm in $vmsInResourceGroup) {
  9. $properties = @{
  10. "status" = "Disabled"
  11. "taskType" = "ComputeVmShutdownTask"
  12. "dailyRecurrence" = @{"time" = $shutdown_time }
  13. "timeZoneId" = $shutdown_timezone
  14. "notificationSettings" = @{
  15. "status" = "Disabled"
  16. "timeInMinutes" = 00
  17. }
  18. "targetResourceId" = $vm.Id
  19. }
  20. $scheduleName = "shutdown-computevm-" + $vm.Name
  21. New-AzResource -ResourceId ("/subscriptions/{0}/resourceGroups/{1}/providers/microsoft.devtestlab/schedules/$scheduleName" -f (Get-AzContext).Subscription.Id, $resourcegroup) -Location $vm.Location -Properties $properties -Force
  22. }
  23. }

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

  • 输出 *:


的数据

展开查看全部

相关问题