客户有这样的需求:每天需要对VM的数据进行备份,但如果备份的时间超过一定的天数,需要进行清除。
本文也是在前一篇Azure Blob Snapshot上的优化。
"Azure blob Storage Snapshot"里,删除Snapshot的思路是遍历所有Storage Account,找到所有的vhd文件,看看是否有Snapshot,如果有判断是否超过14天,如果超过则删除,如果没有超过,则保留。
本文的思路是:
获取所有的虚拟机,判断虚拟机是否运行,如果运行,获取这台虚拟机上所有的硬盘。
如果硬盘的Snapshot超过我们给定的时间,删除,否则不做操作。
具体的脚本如下:
1 function DeleteOlderSnapshot { 2 [CmdletBinding()] 3 param ( 4 [Parameter (Mandatory=$True, 5 ValueFromPipeLine=$True, 6 HelpMessage="BeforeTheDayWillBeDelete")] 7 8 [String] $Day, 9 [switch] $LogErrors 10 ) 11 BEGIN{ 12 Write-Verbose "Error Log will Be $ErrorLog" 13 } 14 Process 15 { 16 17 $vms = Get-AzureVM 18 $now = Get-Date 19 foreach ($vm in $vms) 20 { 21 if($vm.Status -eq "ReadyRole") 22 { 23 $osblobname = ($vm.VM.OSVirtualHardDisk).MediaLink.ToString().Split("/")[-1] 24 $osblobcontainer = ($vm.VM.OSVirtualHardDisk).MediaLink.ToString().Split("/")[-2] 25 $osblobsa = ($vm.VM.OSVirtualHardDisk).MediaLink.ToString().Split("/")[-3].Split(".")[0] 26 27 $storagekey = (Get-AzureStorageKey -StorageAccountName $osblobsa).Primary 28 $ctr = New-AzureStorageContext -StorageAccountName $osblobsa -StorageAccountKey $storagekey -Environment AzureChinaCloud 29 30 $blobs = Get-AzureStorageBlob -Container $osblobcontainer -Context $ctr | Where-Object {$_.Name -match $osblobname} 31 32 foreach ($blob in $blobs) 33 { 34 if($blob.ICloudBlob.IsSnapshot) 35 { 36 37 $diff = [datetime]::FromBinary($now.Ticks-$blob.SnapshotTime.Ticks) 38 write-host $blob.name "is a snapshot" "snapshot time is" $diff.DayOfYear "days" 39 if ( $diff.dayofyear -ge $Day) 40 { 41 42 write-host "delete" 43 $blob.ICloudBlob.Delete() 44 } 45 46 }else{ 47 write-host $blob.Name "is original disk" 48 } 49 } 50 51 $count = $vm.VM.DataVirtualHardDisks.Count 52 53 for($i=0;$i -lt $count;$i++) 54 { 55 $datablobname = ($vm.VM.DataVirtualHardDisks)[$i].MediaLink.ToString().Split("/")[-1] 56 $datablobcontainer = ($vm.VM.DataVirtualHardDisks)[$i].MediaLink.ToString().Split("/")[-2] 57 $datablobsa = ($vm.VM.DataVirtualHardDisks)[$i].MediaLink.ToString().Split("/")[-3].Split(".")[0] 58 $storagekey = (Get-AzureStorageKey -StorageAccountName $datablobsa).Primary 59 $ctr = New-AzureStorageContext -StorageAccountName $datablobsa -StorageAccountKey $storagekey -Environment AzureChinaCloud 60 61 $blobs = Get-AzureStorageBlob -Container $datablobcontainer -Context $ctr | Where-Object {$_.Name -match $datablobname} 62 foreach ($blob in $blobs) 63 { 64 if($blob.ICloudBlob.IsSnapshot) 65 { 66 67 $diff = [datetime]::FromBinary($now.Ticks-$blob.SnapshotTime.Ticks) 68 write-host $blob.name "is a snapshot" "snapshot time is" $diff.DayOfYear "days" 69 if ( $diff.dayofyear -ge $Day) 70 { 71 72 write-host "delete" 73 $blob.ICloudBlob.Delete() 74 } 75 76 }else{ 77 write-host $blob.Name "is original disk" 78 } 79 } 80 } 81 } 82 } 83 84 } 85 end {} 86 } 87 DeleteOlderSnapshot -Day 2