Delete an azure VM using PowerShell

Source: Internet
Author: User

See the headline estimate a lot of people will think this thing also want to write a blog, can be more water point


hahaha, of course not so simple, but not too difficult, this time to introduce is really how to delete the virtual machine in Azure, the removal of the virtual machine itself is a simple and easy task


It is absolutely true that the mouse click on the portal is not deleted. But because Azure compute and storage is detached, deleting a virtual machine actually simply removes the compute power of azure, itself Azure OS disk, data disk, Nic These are also retained in the azure environment


The benefits of doing this are obvious and can prevent your data from being lost due to VM deletion, and it is also recommended to keep the disk after the production environment deletes the VM, waiting for the confirmation data to be deleted before removing the disk from the storage account or the managed disk.


However, sometimes we are very clear to the VM and related information completely removed, but the normal removal of the VM process we need to manually delete the VM, and then delete the disk, delete the network card, public IP and so on these need to be done manually, however, many times the user does not actually have this habit


Many users also do not know how to delete these legacy resources, often think that the removal of VMS is all right, the result is often the azure environment will be left a very large number of disks, network cards, public IP and other resources, on the one hand, resulting in additional costs, on the other hand also makes the azure environment look messy


The script you share today can help you avoid this problem, it's very simple

1. Deleting VMS

2. Remove the NIC associated with the VM

3. Remove the public IP associated with the NIC

4. Delete the OS disk associated with the VM

5. Delete the data disks associated with the VM


It is important to note that currently only support the unmanaged disk, but also note that the data disk these scripts will be all deleted, so before running to be careful, please make sure that the VM related things you do not need to run the script!!


The following is the complete code

param  ([Parameter (mandatory =  $false)][switch] $AzureMoonCake, [Parameter (mandatory = $ False)][switch] $DoNotLogin, [parameter (mandatory =  $true)][string] $ResourceGroupName, [Parameter ( mandatory =  $true)][string] $VMName) function write-datetimemessage{param  ([Parameter ( mandatory =  $false)][switch] $Warning, [parameter (mandatory =  $true)][string] $Message, [ Parameter (mandatory =  $false)][string] $ForegroundColor) if  ($Warning) {write-warning  ($ ( get-date -uformat  '%y/%m/%d %h:%m:%s ')  +   *   +  $Message)}else{ if  ($ForegroundColor) {write-host  ($ (get-date -uformat  '%y/%m/%d %h:%m:%s ')  +    *   +  $Message)  -ForegroundColor  $ForegroundColor}else{write-host  ( $ (get-date -uformat  '%y/%m/%d %h:%m:%s ')  +  " * "  +  $Message)}}} Function write-error0message{write-datetimemessage -message  $Error [0]. exception.message -foregroundcolor red}function remove-azuredisk{param  ([Parameter ( mandatory =  $true)][string] $DiskURI) $DiskURIWithHttps = $DiskURIif   ($DiskURI. StartSWITH ("https:// ") {$DiskURI  =  $DiskURI. Replace (" https://", " ") if  ($AzureMoonCake) {$EndPoint  =  blob.core.chinacloudapi.cn "}else{$EndPoint  = " Blob.core.windows.net "} $StorageAccountName  =   $DiskURI. substring (0,  $DiskURI. indexof ($EndPoint)  - 1) $StorageAccount  =  Get-azurermstorageaccount | ? { $_. storageaccountname -eq  $StorageAccountName  }if  (($StorageAccount  -eq  $null)  -or  ($StorageAccount. count -gt 1)) {Write-datetimemessage -warning -message   "Can ' t find storage account  $StorageAccountName,  pls check"}else{$Context  =  $StorageAccount. context$diskname =  $DiskURI. Substring ($DiskURI. LastIndexOf ("/")  + 1,  $DiskURI. length - $ Diskuri.lastindexof ("/")  - 1) if  ($DiskName  -eq  $null) {write-datetimemessage - warning -message  "Can ' t get disk name from disk uri, pls  Check "}else{$ContainerName  =  $DiskURI. Replace ("/$DiskName ", " ") $ContainerName = $ Containername.substring ($ContainerName. LastIndexOf ("/")  + 1,  $ContainerName .length -  $ContainerName. LastIndexOf ("/")  - 1) if  ($ContainerName  -eq  $null) { write-datetimemessage -warning -message  "Can ' T get container name from  disk uri, pls check "}else{$Blob  = get-azurestorageblob -blob $ diskname -container  $ContainerName  -Context  $Contextif   ($Blob  -eq  $null) { write-datetimemessage -warning -message  "Can ' T&NBsp;get disk blob  $DiskName,  pls check "}else{try{$Error. Clear () Remove-azurestorageblob  -Blob  $DiskName  -Container  $ContainerName  -Context  $Context  -force - erroraction  ' Stop ' write-datetimemessage -message  "remove disk  $DiskURIWithHttps   Successfully! "} catch{write-error0message}}}}}}else{write-datetimemessage -warning -message  "Something  Wrong, the disk uri is not valid "}} #Login  Azure with ARM  Modeimport-module azurerm.profile$error.clear () if  (! $DoNotLogin) {if  ($AzureMoonCake) { write-datetimemessage -warning -message  "Current environment is azure china (mooncake) "login-azurermaccount -environmentname azurechinacloud}else{write-datetimemessage - warning -message  "Current environment is azure global" Login-AzureRmAccount}if   ($? -Eq  $true) {write-datetimemessage -message  "login succeeded!"  -foregroundcolor cyan}else{write-error0messagebreak}}else{$CurrentSubscription  =  get-azurermsubscriptionif  ($CurrentSubscription  -eq  $null) {write-datetimemessage -warning  -Message  "didn ' t find any subscription for now! please login" break}}# $Subscriptions  = get-azurermsubscription#get all publicip,vnet,networkinterfaces$ allpublicips = get-azurermpublicipaddress$allvirtualnetworks = get-azurermvirtualnetwork$ allnetworkinterfaces = get-azurermnetworkinterfacetry{$Error. Clear () $VM  = GET-AZURERMVM  -ResourceGroupName  $ResourceGroupName  -Name  $VMName  -ErrorAction  ' Stop ' if  ($VM  -eq  $null) {write-datetimemessage -warning -message  "no vm named  $VMName  found in  resource group  $ReSourcegroupname "exit}else{$VMNics  =  $VM .networkprofile.networkinterfaces$vmosdisk =  $VM. storageprofile.osdisk$vmdatadisks =  $VM. storageprofile.datadiskswrite-datetimemessage -message  "trying to remove vm $ VMName "remove-azurermvm -resourcegroupname  $ResourceGroupName  -Name  $VMName  -force  -ErrorAction  ' Stop ' | out-nullwrite-datetimemessage -message  "remove vm  $VMName  successfully!" write-datetimemessage -message  "Trying to remove vm nic (s) ..." foreach  ($ vmnic in  $VMNics) {$Nic  =  $AllNetworkInterfaces  | ? { $_.id -eq   $VMNic .id }if  ($Nic  -eq  $null) {write-datetimemessage -warning -message   "Can ' t find nic id $ ($VMNic. ID)" break}else{$PublicIPID  = $ Nic.ipconfigurations.publicipaddress.idremove-azurermnetworkinterface -resourcegroupname  $Nic .resourcegroupname -name  $Nic .name -force -erroraction  ' Stop ' write-datetimemessage -message  ' remove nic $ ($Nic. Name)  successfully! " if  ($PublicIPID  -ne  $null) {$PublicIP  =  $AllPublicIPs  | ? { $_.id  -eq  $PublicIPID  }if  ($PublicIP  -eq  $null) {write-datetimemessage -warning  -Message  "Something wrong, can ' t find public ip with id $ Publicipid "}else{write-datetimemessage -message  (" find public ip {0} associated  with nic {1}, trying to remove it " -f  $PublicIP. name, $ Nic.name) remove-azurermpublicipaddress -resourcegroupname  $PublicIP. Resourcegroupname -name   $PublicIP .name -force -erroraction  ' Stop ' write-datetimemessage -message  ' Remove  public ip $ ($PublicIP. NaMe)  successfully! "}}}} write-datetimemessage -message  "Trying to remove os disk ..." if  ($ vmosdisk.vhd -eq  $null) {write-datetimemessage -message  "vm  $VMName  is using  managed disk "}else{$VMOSDiskURI  =  $VMOSDisk. vhd.uriremove-azuredisk -diskuri $ vmosdiskuriwrite-datetimemessage -message  "Trying to remove data disk ..." if   ($VMDataDisks  -ne  $null) {foreach  ($VMDataDisk  in  $VMDataDisks) {Remove-azuredisk  -DiskURI  $VMDataDisk .vhd.uri}}}write-datetimemessage -message  "all done. thanks "}}catch{write-error0message}


Attached to the operation, the parameters of the total no two will not introduce the HA, all can understand

Delete an azure VM using PowerShell

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.