Search code examples
azurepowershellazure-automationfilesharerunbook

Is it possible to use Azure Automation Runbook to delete another Runbook output (an Azure File share snapshot)?


I want to use the runbook to delete another runbook output (an Azure File Share snapshot).

Is it possible? If you know something, please write something at here

Runbook 1: Create an Azure File share snapshot

$context = New-AzureStorageContext -StorageAccountName -StorageAccountKey 
$share = Get-AzureStorageShare -Context 
$context -Name "sharefile" 
$snapshot = $share.Snapshot()

Runbook 2: Delete the Azure runbook output. The problem with this is that it deletes all snapshots rather than just delete the one created by the first runbook.

$allsnapshots = Get-AzureStorageShare -Context $context | Where-Object { $_.Name -eq "sharefile" -and $_.IsSnapshot -eq $true } 
foreach($snapshot in $allsnapshots){ 
    if($snapshot.SnapshotTime -lt (get-date).Add·Hours()){ 
        $snapshot.Delete()
    }
}

Solution

  • The sample code is as below, I test it in runbook and works well(create a snapshot, and then delete it after 3 minutes), and the other snapshots have no effect.

    code in my powershell runbook:

    param(
    [string]$username,
    [string]$password,
    [string]$filesharename
    )
    
    $context = New-AzureStorageContext -StorageAccountName $username -StorageAccountKey $password
    $share = Get-AzureStorageShare -Context $context -Name $filesharename
    $s = $share.snapshot()
    
    #get the snapshot name, which is always a UTC time formated value
    $s2= $s.SnapshotQualifiedStorageUri.PrimaryUri.ToString()
    
    #the $snapshottime is actually equal to snapshot name
    $snapshottime = $s2.Substring($s2.IndexOf('=')+1)
    write-output "create a snapshot"
    write-output $snapshottime
    
    #wait 180 seconds, then delete the snapshot 
    start-sleep -s 180
    
    write-output "delete the snapshot"
    $snap = Get-AzureStorageShare -Context $context -SnapshotTime $snapshottime -Name $filesharename 
    $snap.Delete()
    
    write-output "deleted successfully after 3 minutes"
    

    after it's running, you can see the snapshot is created in azure portal:

    enter image description here

    After it completes, the specified snapshot is deleted(you may need to open a new webpage to see the change due to some cache issue)

    the output in runbook:

    enter image description here