【发布时间】:2020-05-30 06:13:13
【问题描述】:
引起我注意的是,如果您创建一个新 VM,然后删除它(及其关联的资源),您确实没有实际上删除了相应的 VHD 文件 -- 该文件是留在 blob 存储中,阻止配置具有相同主机名的新机器,并且还会为浪费和未使用的存储花费真金白银。我希望将 VHD 连同 VM 一起删除。
我在哪里可以找到关于如何处理这个问题的当前智慧的好文章?我只能找到 2013 年之前的参考资料,这些参考资料显然是针对“经典”版本的。
我编写了以下代码来尝试纠正这种情况。我有两个用例,首先我必须清除所有累积的垃圾,然后我“只是”需要确保在删除每台未来的机器后进行清理。
write-output("Removing orphaned disks for hostname ""$hostname"" ...")
$storageContext = (Get-AzureRmStorageAccount | Where-Object{$_.StorageAccountName -match $azureStorage}).Context
$storageBlob = Get-AzureStorageBlob -Context $storageContext -Container "vhds"
$vhdList = $storageBlob | Where-Object{$_.Name -match "$hostname"}
foreach($disk in $vhdList) {
$diskname = $disk.Name
write-output("Removing VHD ""$diskname"" ...")
Remove-AzureDisk -Diskname "$diskname" -DeleteVHD
write-output("Removed VHD ""$diskname"" ... [OK]")
}
write-output("Removed orphaned disks ... [OK]")
现在,当我运行它时,我会得到我希望看到的 VHD 文件的漂亮列表(以及一些相应的“*.status”文件)。但是,Remove-AzureDisk 命令会产生错误Remove-AzureDisk : ResourceNotFound: The disk with the specified name does not exist,因此它并没有真正起作用。
您会注意到我在中途从新的“ARM”命令切换到“经典”版本——这可能是我的问题的一部分,但我没有运气想出更好的命令.
更新:
这似乎可以解决问题:
# Verify that the OS VHD does not already exist
write-output("Checking for blocking VHD's ...")
$storageContext = (Get-AzureRmStorageAccount | Where-Object{$_.StorageAccountName -match $azureStorage}).Context
$storageBlob = Get-AzureStorageBlob -Context $storageContext -Container "vhds"
$vhdList = $storageBlob | Where-Object{$_.Name -match "$hostname"}
if ($vhdList) {
write-output("There is an existing VHD blocking host ""$hostname"" in storage container ""$($storageContext.BlobEndPoint)vhds""):")
foreach($vhdName in $vhdList.Name) {
write-output("- $vhdName")
}
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | out-null
$answer = [System.Windows.Forms.MessageBox]::Show("There is an existing VHD blocking host ""$hostname"" in storage container ""$($storageContext.BlobEndPoint)vhds"").`nDo you wish to remove the existing VHD file?" , "Create New VM" , $MB_YESNO)
if ($answer -eq "YES" ) {
# Remove VHD files
foreach($diskName in $vhdList.Name) {
write-output("- Removing VHD ""$diskName""")
Remove-AzureStorageBlob -Blob $diskName -Container "vhds" -Context $storageContext
}
write-output("Checked for blocking VHD's ... [OK]")
} else {
exit(331)
}
}
【问题讨论】:
-
如何删除虚拟机?你用什么命令?
-
为了测试,我通过 Web 界面删除了 VM。据我(最近)了解,这会产生将 VHD 留在原地的不良影响。
标签: powershell azure azure-powershell azure-resource-manager