[Azure]使用Powershell刪除ARM模式下單臺虛擬機及相關資源(非託管磁盤)

對於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;

運行結果:


發佈了264 篇原創文章 · 獲贊 1萬+ · 訪問量 61萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章