From 8479a4c776f2c6519743689bf867623c81d8dae1 Mon Sep 17 00:00:00 2001 From: Raimond Kuipers Date: Fri, 26 Jul 2019 10:42:58 +0200 Subject: [PATCH] Create AutomatedSnapshots.ps1 --- AutomatedSnapshots.ps1 | 48 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 AutomatedSnapshots.ps1 diff --git a/AutomatedSnapshots.ps1 b/AutomatedSnapshots.ps1 new file mode 100644 index 0000000..4160bd0 --- /dev/null +++ b/AutomatedSnapshots.ps1 @@ -0,0 +1,48 @@ +$connectionName = "AzureRunAsConnection" +try +{ + # Get the connection "AzureRunAsConnection " + $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName + + "Logging in to Azure..." + Add-AzureRmAccount ` + -ServicePrincipal ` + -TenantId $servicePrincipalConnection.TenantId ` + -ApplicationId $servicePrincipalConnection.ApplicationId ` + -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint +} +catch { + if (!$servicePrincipalConnection) + { + $ErrorMessage = "Connection $connectionName not found." + throw $ErrorMessage + } else{ + Write-Error -Message $_.Exception + throw $_.Exception + } +} + + +$disks=Get-AzureRmDisk -ResourceGroupName "MyResourceGroup" | Select Name,Tags,Id,Location,ResourceGroupName ; +foreach($disk in $disks) +{ + foreach($tag in $disk.Tags) + { + if($tag.Snapshot -eq 'True') + { + $snapshotconfig = New-AzureRmSnapshotConfig -SourceUri $disk.Id -CreateOption Copy -Location $disk.Location -AccountType Premium_LRS; + $SnapshotName=$disk.Name+(Get-Date -Format "yyyy-MM-dd"); + $snapshot = New-AzureRmSnapshot -Snapshot $snapshotconfig -SnapshotName $SnapshotName -ResourceGroupName $disk.ResourceGroupName; + + + } + } +} + +$dte = Get-Date; +$dte = $dte.AddDays(-7); +$snapshots=Get-AzureRmSnapshot -ResourceGroupName "MyResourceGroup" | Where-Object {$_.Timestamp -gt $dte} +foreach($snapshot in $snapshots) +{ + Remove-AzureRmSnapshot -ResourceGroupName "MyResourceGroup" -SnapshotName $snapshot.Name -Force; +}