我尝试使用 Azure powershell 获取虚拟机名称(例如:demovm01
,其中虚拟机名称为 demovm
,后缀为 01
>.
我想要获取输出并自动附加新后缀 02
(如果 01
已存在)。
获取虚拟机名称的示例脚本:
$getvm = Get-AzVM -Name "$vmname" -ResourceGroupName "eodemofunction" -ErrorVariable notPresent -ErrorAction SilentlyContinue
if ($notPresent) {
Write-Output "VM not found. Creating now"
}
else {
Write-Output "VM exists."
return $true
}
我希望能够将这个新的虚拟机名称注入(inject)到arm部署中进行部署
最佳答案
这应该可以做到。将递增,直到找不到 VM 为止,并使用简单的 -replace
注入(inject)到您的 json 文件中。还将返回 Azure 中已存在的所有 thr VM 值
$i=1
$vmname_base = "vmserver"
$VMexists = @()
do {
#invert int value to double digit string
$int = $i.tostring('00')
$getvm = Get-AzVM -Name "$vmname_base$int" -ResourceGroupName "eodemofunction" -ErrorVariable notPresent -ErrorAction SilentlyContinue
if ($notPresent) {
Write-Output "VM not found. Creating now"
Write-Output "VM created name is $vmname_base$int"
#Set condition to end do while loop
VMcreated = "true"
#commands to inject to json here. I always find replace method the easiest
$JSON = Get-Content azuredeploy.parameters.json
$JSON = $JSON -replace ("Servername","$vmname_base$int")
$JSON | Out-File azuredeploy.parameters.json -Force
}
else {
Write-Output "VMexists."
# Add existing VM to array
$VMexists += "$vmname_base$int"
# Increment version, ie. 01 to 02 to 03 etc
$i++
}
} while ($VMcreated -ne "true")
return $VMexists
关于azure - 部署arm模板前检查Azure VM名称是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57598771/