Creating a snapshot everyday with an automated task is easy. But what if you do not want to end up with endless snapshots without manually deleting them?
Here is a powershell script which uses the windows cli master to delete every snapshot that is older than X days:
#$count_days indicates after how many days a snapshot shall be deleted
$count_days = 11;
#all snapshots set in var $snapshots as string
$snapshots = profitbricks snapshot list | Out-String;
#$count_chars indictaes the chars in the 2nd line. used to measure and split the strings
$count_chars = ((profitbricks snapshot list)[1]).Length + 2;
#skip the first 11 chars and 3 first lines (not part of the snapshots)
$snapshots = $snapshots.substring(11 + $count_chars * 3);
#read snapshot-IDs and set them in $id_array as well as the date in $date_array
while ($snapshots.Length -gt 10){
$count_skip = $count_chars - 33;
[string[]] $id_array += $snapshots.substring(0,36) | Out-String;
[string[]] $date_array += $snapshots.substring($count_skip,10) | Out-String;
$snapshots = $snapshots.substring($count_chars);
}
#todays date
$today = Get-Date -format o | Out-String;
$today = $today.Substring(0,10);
#loop to compare time_spans
for ($i=0;$i -lt $id_array.Length;$i++){
$time_span = [datetime]$today - [datetime]$date_array[$i];
#look for the number of days
if ($time_span.TotalDays -gt $count_days){
#read snapshot-ID
$snap_del = $id_array[$i].substring(0,$id_array[$i].Length-2).ToString();
#delete snapshot
profitbricks snapshot delete -f -i "$snap_del"
}
}
Save it as a ".ps1" file. Windows task is as following:
program: %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe
arguments: -noprofile -NoLogo -noninteractive -ExecutionPolicy Bypass -File "C:\Your path\scriptname.ps1"
path: C:\Your path