How to rotate snapshots in windows using powershell for Google Cloud Platform

Color Orange
2 min readAug 9, 2018

--

Hello Friends,

I came across a scenario where I wanted to create daily incremental snapshots of GCE and cleanup old snapshots for easy management.

I did lots of search but there was no big help since all backup-scripts I found were written in unix/linux language. I just could not use them on windows.

So I ended up writing my own windows Powershell script which takes daily backup and removes old ones. I thought I should share this and it will help others to cut down the chase.

Prerequisite

As a prerequisite, you are required to have installed Google Cloud SDK ( download reference ) and logged into CLI ( gcloud auth login )

Step 1

Download the win-bash utility from here

Once downloaded extract in your C: drive and then configure Path in the environment variable, so those commands gets available for execution.

Step 2

Use notepad or your favorite text editor for writing script.

Use the below script and modify as per your need. Change/Update parameters as needed.

And finally save the script with extension “.ps1” ( power shell ), using powershell you can run it.

$projectset = gcloud config set project <project-id>;
$snap = gcloud compute snapshots list — uri;

For ($i=0; $i -lt $snap.length; $i++){

# get the date that the snapshot was created
$SNAPSHOT_DATETIME = gcloud compute snapshots describe $snap[$i] | grep “creationTimestamp” | cut -d “ “ -f 2 | tr -d “‘”

# format the date
$SNAPSHOT_DATETIME= (Get-Date $SNAPSHOT_DATETIME -Format “yyyMMdd”)

echo “================================”;
echo $snap[$i];
echo $SNAPSHOT_DATETIME;

# get the expiry date for snapshot deletion (currently 4 days)
$SNAPSHOT_EXPIRY=(get-date).AddDays(-4).ToString(“yyyMMdd”)

echo “ expiry = $SNAPSHOT_EXPIRY snap date = $SNAPSHOT_DATETIME”;

if($SNAPSHOT_EXPIRY -gt $SNAPSHOT_DATETIME){
# delete the snapshot
$deleted = gcloud compute snapshots delete $snap[$i] — quiet
echo “delete “ + SNAPSHOT_DATETIME + “ days diff = “ + ($SNAPSHOT_EXPIRY-$SNAPSHOT_DATETIME)

} else {
echo “No delete required”
}

echo “================================”;
}

Above script will clean up snapshots which are older than 4 days. You should change as per your need. You can schedule above script in windows task schedule to execute on required frequency.

Note : Above script is not in 100% PowerShell script language. If you like to write in 100% PowerShell language then here is the reference to PowerShell language commands which are alternative to unix/linux commands such as cut, tr etc

I hope this helps and save your time :)

--

--