编写PowerShell脚本:选择Azure VM并存储其名称与资源组信息
PowerShell Script to Select Azure VM and Store Details
Got it, here's a practical PowerShell script that does exactly what you're asking for—plus some basic error handling to make sure it behaves smoothly even if the user enters invalid input:
# First, get all VMs in the current Azure subscription using AzureRm module $allVMs = Get-AzureRmVM # Check if any VMs exist in the subscription if (-not $allVMs) { Write-Host "No virtual machines found in the current Azure subscription." -ForegroundColor Red exit } # Display VMs with numbered list for selection Write-Host "`nList of Virtual Machines in your subscription:" -ForegroundColor Cyan for ($i = 0; $i -lt $allVMs.Count; $i++) { Write-Host "$($i+1). VM Name: $($allVMs[$i].Name) | Resource Group: $($allVMs[$i].ResourceGroupName)" } # Prompt user for selection, with input validation do { $userInput = Read-Host "`nEnter the number of the VM you want to select" # Check if input is a valid number within the list range if ($userInput -match '^\d+$' -and [int]$userInput -ge 1 -and [int]$userInput -le $allVMs.Count) { $selectedIndex = [int]$userInput - 1 # Convert to zero-based index break } else { Write-Host "Invalid input! Please enter a number between 1 and $($allVMs.Count)." -ForegroundColor Yellow } } while ($true) # Store selected VM's name and resource group in variables $selectedVMName = $allVMs[$selectedIndex].Name $selectedResourceGroup = $allVMs[$selectedIndex].ResourceGroupName # Confirm the selection (optional but helpful for user feedback) Write-Host "`nSuccessfully selected:" -ForegroundColor Green Write-Host "VM Name: $selectedVMName" Write-Host "Resource Group: $selectedResourceGroup"
Key Features Explained:
- VM Check: First verifies if there are any VMs in the subscription—no need to proceed if there's nothing to select!
- Numbered List: Uses a loop to display each VM with a clear, user-friendly number (1-based instead of 0-based, since users don't think in zero indexes).
- Input Validation: Makes sure the user enters a valid number that's within the range of available VMs, so you avoid errors from typos or invalid entries.
- Variable Storage: Stores the selected VM's name and resource group in separate variables that you can use for subsequent operations (like starting/stopping the VM, modifying settings, etc.).
Quick Note:
If you're using the newer Az module (recommended over AzureRm, which is deprecated), just replace Get-AzureRmVM with Get-AzVM in the script—it will work the same way.
内容的提问来源于stack exchange,提问作者szikk
相关产品推荐
相关产品推荐

