如何按每10台一批将30台虚拟机分配至3个Azure资源组
Perfecting Your Azure VM Deployment Script
Got it, let's tweak your PowerShell script to deploy 30 VMs evenly across 3 resource groups (10 per RG) with automatic RG switching after every 10 deployments. Here's the refined, production-ready version with clear logic:
Step-by-Step Explanation & Code
First, we'll add a resource group index tracker and a per-RG VM counter to handle the automatic switch. We'll also fill in the mandatory parameters for New-AzVM (your original snippet was missing critical details like VM size, location, and network config—without these, the script won't run).
# Connect to your Azure account (uncomment if not already connected) # Connect-AzAccount # Define your resource groups and VM names $resourceGroupNames = @('Rg1', 'Rg2', 'Rg3') $vmNames = @('vm1','vm2','vm3','vm4','vm5','vm6','vm7','vm8','vm9','vm10', 'vm11','vm12','vm13','vm14','vm15','vm16','vm17','vm18','vm19','vm20', 'vm21','vm22','vm23','vm24','vm25','vm26','vm27','vm28','vm29','vm30') # Initialize tracking variables $currentRGIndex = 0 $vmCountInCurrentRG = 0 $location = 'eastus' # Update to your preferred region $vmSize = 'Standard_D2s_v3' # Update to your desired VM size $adminUsername = 'azureuser' # Set your admin username $adminPassword = ConvertTo-SecureString 'YourStrongPassword123!' -AsPlainText -Force # Use a secure password in production foreach ($vmName in $vmNames) { # Get the current resource group name $currentRG = $resourceGroupNames[$currentRGIndex] # Verify resource group exists (create if missing) if (-not (Get-AzResourceGroup -Name $currentRG -ErrorAction SilentlyContinue)) { New-AzResourceGroup -Name $currentRG -Location $location Write-Host "Created resource group: $currentRG" } # Create VM configuration $vmConfig = New-AzVMConfig -VMName $vmName -VMSize $vmSize $vmConfig = Set-AzVMOperatingSystem -VM $vmConfig -Windows -ComputerName $vmName -Credential (New-Object System.Management.Automation.PSCredential ($adminUsername, $adminPassword)) -ProvisionVMAgent -EnableAutoUpdate $vmConfig = Set-AzVMSourceImage -VM $vmConfig -PublisherName 'MicrosoftWindowsServer' -Offer 'WindowsServer' -Skus '2022-Datacenter' -Version latest # Add a public IP (optional, remove if not needed) $publicIp = New-AzPublicIpAddress -Name "$vmName-ip" -ResourceGroupName $currentRG -Location $location -AllocationMethod Dynamic $nic = New-AzNetworkInterface -Name "$vmName-nic" -ResourceGroupName $currentRG -Location $location -SubnetId (Get-AzVirtualNetwork -Name 'vnet-eastus' -ResourceGroupName $currentRG).Subnets[0].Id -PublicIpAddressId $publicIp.Id $vmConfig = Add-AzVMNetworkInterface -VM $vmConfig -Id $nic.Id # Deploy the VM New-AzVM -ResourceGroupName $currentRG -Location $location -VM $vmConfig Write-Host "Successfully deployed VM: $vmName to resource group: $currentRG" # Update counters and switch RG if needed $vmCountInCurrentRG++ if ($vmCountInCurrentRG -eq 10) { $vmCountInCurrentRG = 0 # Only increment RG index if there's another RG available if ($currentRGIndex -lt ($resourceGroupNames.Count - 1)) { $currentRGIndex++ Write-Host "Switching to next resource group: $($resourceGroupNames[$currentRGIndex])" } } }
Key Improvements:
- Automatic RG Switching: Uses
$currentRGIndexand$vmCountInCurrentRGto track when to move to the next resource group after 10 VMs. - RG Validation: Checks if the resource group exists and creates it if missing (no more "resource group not found" errors).
- Complete VM Configuration: Fills in all mandatory parameters for
New-AzVM(OS image, credentials, network setup) so the script is ready to run with minimal tweaks. - Safety Checks: Includes a guard clause to avoid incrementing the RG index beyond the available resource groups (useful if you ever adjust the number of RGs/VMs).
Notes:
- Update variables like
$location,$vmSize,$adminUsername, and$adminPasswordto match your environment. - If you're using Linux VMs, adjust the
Set-AzVMOperatingSystemparameters to use-Linuxinstead of-Windows. - The virtual network (
vnet-eastus) is assumed to exist in each resource group—if not, add logic to create it before deploying VMs, or use a shared VNET.
内容的提问来源于stack exchange,提问作者ferj
相关产品推荐
相关产品推荐

