可以通过运行附件中PowerShell脚本文件RemoveVMandDisk.ps1批量删除VM和Disk,详细代码如下:
param($serviceName)
echo "Starting remove all vms of service $serviceName"
#$serviceName="erictest"
echo "Get all DiskNames of all VMs of service $serviceName."
$azureDiskNames= Get-AzureDisk| where{$_.AttachedTo -ne $null -and $_.AttachedTo.HostedServicename.StartsWith($serviceName)} | select DiskName
$azureDiskNames
if($azureDiskNames -eq $null -or $azureDiskNames.Count -le 0){
echo "No VMs wanted to Remove."
exit
}
echo "`r`nStarting remove all VMs of service $serviceName..."
Get-AzureVM | where{$_.ServiceName.StartsWith($serviceName)} | Remove-AzureVM -Verbose
#It spends time to remove VM on backend.
echo "Waiting Removing VM on backend..."
Start-Sleep -Seconds 120* $azureDiskNames.Count
echo "`r`nStarting remove all related disks..."
foreach($diskName in $azureDiskNames){
Get-AzureDisk | where {$_.DiskName -eq $diskName.DiskName } | Remove-AzureDisk -DeleteVHD -Verbose
}
echo "`r`nStarting remove all services"
Get-AzureService | where{$_.ServiceName.StartsWith($serviceName)} | Remove-AzureService -Force -Verbose
运行步骤:
- 打开Windows Azure PowerShell, 并导入订阅信息(Subscription)。
关于如何安装和配置Azure PowerShell,请参考http://www.windowsazure.com/en-us/documentation/articles/install-configure-powershell/。
需要注意一点,在执行Get-AzurePublishSettingsFile命令获取Subscription文件的时候,不要使用它自动跳转的Url(这是国外Windows Azure的链接),需要手动输入https://manage.windowsazure.cn/publishsettings/index?client=powershell ,然后登录并获取Subscription文件
- 运行命令 Set-ExecutionPolicy RemoteSigned 更执行策略。
- 执行RemoveVMandDisk.ps1脚本。
语法:RemoveVMandDisk.ps1 <ServiceName> #可以删除以这个ServiceName开头的所有虚机VM
例子:RemoveVMandDisk.ps1 ericwenService
如果您在删除虚机后,删除Disk发生错误“当前磁盘被占用”,可以修改等待后台运行时间:Start-Sleep -Seconds 120* $azureDiskNames.Count
- 您还可以使用命令(Get-AzureDisk| where{ $_.AttachedTo -eq $null } | Remove-AzureDisk -DeleteVHD -Verbose )删除所有未使用(附加到VM上)的磁盘
以上脚本和代码仅供参考,您可以根据您的业务逻辑做调整和修改。