[Azure]使用Powershell删除ARM模式下单台虚拟机及相关资源(非托管磁盘)

时间:2022-09-16 21:47:47

对于ARM虚拟机,删除后,默认会保留磁盘文件,以及网络接口,IP地址等资源。所以如果不手工删除,这些垃圾资源会占用账号的资源,产生额外的话费,因此整理了一个脚本用于删除虚拟机的同时将这些垃圾资源清理掉。

本脚本针对非托管磁盘虚拟机。


脚本如下:

param(
[Parameter(Mandatory = $true)]
[string]$SubscriptionName,

[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,

[Parameter(Mandatory = $true)]
[string]$VMName
)

Function GetResourceNameFromResourceId($resourceId)
{
return $resourceId.Substring($resourceId.LastIndexOf('/') + 1);
}

Function GetResourcePropertyFromResourceId($resourceId, $propertyName)
{
$propertyName = $propertyName + "/";
$rgName = $resourceId.Substring($resourceId.IndexOf($propertyName) + $propertyName.Length);
return $rgName.Substring(0, $rgName.IndexOf("/"));
}

Function GetStorageAccountNameFromVhdUri($vhdUri)
{
$startLength = "https://".Length;
return $vhdUri.Substring($startLength, $vhdUri.IndexOf(".blob.core.chinacloudapi.cn") - $startLength);
}

Function CollectVMInformation($rgName, $vmName)
{
$vmInfo = @{};
$vmInfo.Add("ResourceGroup", $rgName);
$vmInfo.Add("Name", $vmName);

$vm = Get-AzureRmVM -ResourceGroupName $rgName -Name $vmName -ErrorAction Ignore -WarningAction Ignore;
if ($vm -eq $null)
{
return $null;
}

$vmInfo.Add("Size", $vm.HardwareProfile.VmSize);
$vmInfo.Add("Location", $vm.Location);
if ($vm.AvailabilitySetReference -ne $null)
{
$vmInfo.Add("AvailabilitySet", $vm.AvailabilitySetReference.Id);
}

$vmInfo.Add("OSType", $vm.StorageProfile.OsDisk.OsType.ToString());

#network properties
$nicId = ($vm.NetworkProfile.NetworkInterfaces | where {$_.Primary -eq $true}).Id;
if ($nicId -eq $null -and $vm.NetworkProfile.NetworkInterfaces.Count -eq 1)
{
$nicId = $vm.NetworkProfile.NetworkInterfaces[0].Id;
}
$vmInfo.Add("PrimaryNetworkInterfaceId", $nicId);
$secondaryNics = @($vm.NetworkProfile.NetworkInterfaces | where {$_.Primary -eq $false});
$vmInfo.Add("SecondaryNetworkInterfaces", $secondaryNics);

#disk
$vmInfo.Add("OSDisk", $vm.StorageProfile.OsDisk);
$vmInfo.Add("DataDisks", @($vm.StorageProfile.DataDisks));

Write-Host ("{0, -16}: {1}" -f "Name", $vmInfo["Name"]) -ForegroundColor Cyan;
Write-Host ("{0, -16}: {1}" -f "Resource Group", $vmInfo["ResourceGroup"]) -ForegroundColor Cyan;
Write-Host ("{0, -16}: {1}" -f "Size", $vmInfo["Size"]) -ForegroundColor Cyan;
Write-Host ("{0, -16}: {1}" -f "Location", $vmInfo["Location"]) -ForegroundColor Cyan;
Write-Host ("{0, -16}: {1}" -f "OS Type", $vmInfo["OSType"]) -ForegroundColor Cyan;
if ($vmInfo.ContainsKey("AvailabilitySet"))
{
Write-Host ("{0, -16}: {1}" -f "Availability Set", $vmInfo["AvailabilitySet"]) -ForegroundColor Cyan;
}
Write-Host ("{0, -16}: {1}" -f "Primary NIC", $vmInfo["PrimaryNetworkInterfaceId"]) -ForegroundColor Cyan;
foreach ($secondaryNic in $vmInfo["SecondaryNetworkInterfaces"])
{
Write-Host ("{0, -16}: {1}" -f "Secondary NIC", $secondaryNic.Id) -ForegroundColor Cyan;
}
Write-Host ("{0, -16}: {1}" -f "OS Disk", $vmInfo["OSDisk"].Vhd.Uri) -ForegroundColor Cyan;
foreach ($dataDisk in $vmInfo["DataDisks"])
{
Write-Host ("{0, -16}: {1}" -f "Data Disk", $dataDisk.Vhd.Uri) -ForegroundColor Cyan;
}

return $vmInfo;
}

Function DeleteDisk($vhdUri)
{
$storageAccountName = GetStorageAccountNameFromVhdUri $vhdUri;
$containerName = GetResourcePropertyFromResourceId $vhdUri ".blob.core.chinacloudapi.cn";
$blobName = GetResourceNameFromResourceId $vhdUri;
$storage = $allStorageAccounts | where {$_.StorageAccountName -eq $storageAccountName};
Write-Host ("Deleting blob file {0}" -f $vhdUri) -ForegroundColor Yellow;
Remove-AzureStorageBlob -Blob $blobName -Container $containerName -Context $storage.Context -Force;
}

Function DeleteNic($nicId)
{
$nicName = GetResourceNameFromResourceId $nicId;
$rgName = GetResourcePropertyFromResourceId $nicId "resourceGroups";
$nic = Get-AzureRmNetworkInterface -Name $nicName -ResourceGroupName $rgName;
Write-Host ("Deleting network interface {0}" -f $nicName) -ForegroundColor Yellow;
Remove-AzureRmNetworkInterface -Name $nicName -ResourceGroupName $rgName -Force;

$primaryIPCfg = $nic.IpConfigurations | where {$_.Primary -eq $true};
if ($primaryIPCfg.PublicIpAddress -ne $null)
{
DeletePip $primaryIPCfg.PublicIpAddress.Id;
}

$secondaryIPCfgs = $nic.IpConfigurations | where {$_.Primary -eq $false};
foreach ($secondaryIPCfg in $secondaryIPCfgs)
{
if ($secondaryIPCfg.PublicIpAddress -ne $null)
{
DeletePip $secondaryIPCfg.PublicIpAddress.Id;
}
}
}

Function DeletePip($pipId)
{
$rgName = GetResourcePropertyFromResourceId $pipId "resourceGroups";
$ipName = GetResourceNameFromResourceId $pipId;
Write-Host ("Deleting public ip address {0}" -f $ipName) -ForegroundColor Yellow;
Remove-AzureRmPublicIpAddress -Name $ipName -ResourceGroupName $rgName -Force;
}

Function DeleteVM($vmInfo)
{
#basic information
$rgName = $vmInfo["ResourceGroup"];
$vmName = $vmInfo["Name"];

#network
$primaryNicId = $vmInfo["PrimaryNetworkInterfaceId"];
$secondaryNics = $vmInfo["SecondaryNetworkInterfaces"];

#disk
$osDisk = $vmInfo["OSDisk"];
$dataDisks = $vmInfo["DataDisks"];
$avaSetId = $vmInfo["AvailabilitySet"];

Write-Host "Deleting virtual machine..." -ForegroundColor Yellow;
[void](Remove-AzureRmVM -Name $vmName -ResourceGroupName $rgName -Force);

Write-Host "Deleting disks..." -ForegroundColor Yellow;
DeleteDisk $osDisk.Vhd.Uri;

foreach ($dataDisk in $dataDisks)
{
DeleteDisk $dataDisk.Vhd.Uri;
}

Write-Host "Deleting network interfaces..." -ForegroundColor Yellow;
DeleteNic $primaryNicId;
$secondaryNicCount = $secondaryNics.Count;
for ($i = 0; $i -lt $secondaryNicCount; $i++)
{
$secondaryNicId = $secondaryNics[$i].Id;
DeleteNic $secondaryNicId;
}
}

[void](Select-AzureRmSubscription -SubscriptionName $SubscriptionName);
$allStorageAccounts = Get-AzureRmStorageAccount;

Write-Host "Virtual Machine information:" -ForegroundColor Green;
$vmInfo = (CollectVMInformation $ResourceGroupName $vmName);
if ($vmInfo -eq $null)
{
Write-Host "Failed to collect vm information." -ForegroundColor Red;
return;
}

DeleteVM $vmInfo;

Write-Host "Finished" -ForegroundColor Green;

运行结果:

[Azure]使用Powershell删除ARM模式下单台虚拟机及相关资源(非托管磁盘)