Powershell/Azure-CLI - 传递给正则表达式字符串匹配的用户输入变量?

Powershell/Azure-CLI - User input variable passed into regex string match?

我有一个脚本可以自动调整 Azure 中托管 OS 磁盘的大小。目前,我需要在下面标记为 "VM NAME HERE" 的两个位置对 VM 的名称进行硬编码,以使其正常工作。

我想弄清楚如何获取 $vm 的输入并使用它来匹配正则表达式而不是对名称进行硬编码。

可以这样做吗?

# Set the required variables with user input
$vm = Read-Host -Prompt 'Input the name of the target VM'
$rg = Read-Host -Prompt 'Input the name of your Resource Group'
$size = Read-Host -Prompt 'How many GB should the disk be changed to'
$new_snap = Read-Host -Prompt 'Please name the backup snapshot for your OS Disk'

# Locate the OS Disk information based on the name of the VM
$disk_id = (az vm list --query "[].{ name:name, os:storageProfile.osDisk.managedDisk.id }")
$os_disk = $disk_id | Select-String -Pattern '("VM NAME HERE"[_\w\d]+)' | ForEach-Object { 
$_.Matches.Groups[1].Value }
$snap = $disk_id | Select-String -Pattern '([\.\/\-\w\d]+"VM NAME HERE"[_\w\d]+)' | ForEach-Object { 
$_.Matches.Groups[1].Value }

# Create Snapshot
Write-Output "Creating Snapshot: $new_snap"
az snapshot create --resource-group $rg --name $new_snap --source $snap

# Deallocate Target VM
Write-Output "Deallocating VM: $vm"
az vm deallocate --resource-group $rg --name $vm

# Resize Managed Disk
Write-Output "Updating OS Disk size to $size GB"
az disk update --name $os_disk --resource-group $rg --size-gb $size

# Restart Target VM
Write-Output "Restarting VM: $vm"
az vm start --resource-group $rg --name $vm

根据我的测试,我们可以直接使用以下命令获取vm os disk id

$disk_id = (az vm list --query "[?name == '$vm'].storageProfile.osDisk.managedDisk.id" -o tsv)

详情请参考https://www.craigforrester.com/posts/resize-azure-vm-disks-with-azure-cli/