I would like to manage my blob snapshots in azure with a PowerShell script.
I already have a script which creates every hour a snapshot from a blob.
Now I would like to create a query that deletes old snapshots.
If the snapshot is older than 5 days, the last snapshot of the day is to be retained. All snapshots older than 30 days are to be deleted.
How can I do this?
My code which deletes all snapshots after 30 days:
foreach ($CloudBlockBlob in $ListOfBlobs)
{
if ($CloudBlockBlob.IsSnapshot)
{
if ($CloudBlockBlob.SnapshotTime.DateTime -le $RetentionTime )
{
$CloudBlockBlob.Delete()
if (!$?) { Write-Host "Snapshot cannot be deleted. Error on Line " + Get-CurrentLineNumber }
}
}
}
We can use this script to delete snapshot blob older than 5 days:
$deletetime = [datetime]::today.adddays(-5).tostring('yyyyMMdd')
$StorageAccountName = "jasondisk3"
$StorageAccountKey = "m+kQwLuQZiI3LMoMTyAI8dq4qul4s8fAIHGPMTD/AG2j+TPHBpttq5hXRmTaQ=="
$ContainerName = "jasonvm"
$Ctx = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
$ListBlob = Get-AzureStorageBlob –Context $Ctx -Container $ContainerName | Where-Object {$_.ICloudBlob.IsSnapshot -and $_.SnapshotTime -ne $null -and (($_.SnapshotTime.localdatetime).ToString('yyyyMMdd') -lt $deletetime) }
foreach($b in $listblob) {
$b.ICloudBlob.Delete()
}
Note:
This PowerShell will delete all blobs in that container and older than 5 days.
Update :
Here a script to delete one day's snapshots and keep the latest one, please refer to it:
$deletetime = [datetime]::today.adddays(-1).tostring('yyyyMMdd')
$StorageAccountName = "jasondisk3"
$StorageAccountKey = "m+kQwLuQZiI3LMoMTyAI8K40gkOD+ZaTxxxs8fAIHGPMTD/AG2j+TPHBpttq5hXRmTaQ=="
$ContainerName = "jasonvm"
$Ctx = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
$a = Get-AzureStorageBlob -Container $ContainerName -Context $Ctx | select -ExpandProperty name -Unique
foreach($c in $a){$d = $c.split('.')[0]; $e = $d +'*' ; $f = Get-AzureStorageBlob –Context $Ctx -Container $ContainerName -blob $e | Where-Object {$_.ICloudBlob.IsSnapshot -and $_.SnapshotTime -ne $null -and (($_.SnapshotTime.localdatetime).ToString('yyyyMMdd') -eq '20171110') }; $ff = $f[-1];foreach($qq in $f){if($qq -ne $ff){$qq.ICloudBlob.Delete()}} }
You can modify it to delete other days, add a foreach
to date.
Hope this helps:)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.