I am close to what I need but I am missing something because the snapshot isn't removing. I think its the datetime string I have isn't all the way correct, so I am here for a little help. Here is my current PS code.
rg = 'snapshots'
$snapshotnames = (Get-AzureRmSnapshot -ResourceGroupName $rg).name
foreach($snapname in $snapshotnames)
{
Get-AzureRmSnapshot -ResourceGroupName $rg -SnapshotName $snapname |
?{($_.TimeCreated).ToString('yyyy-MM-dd') -lt ([datetime]::Today.AddDays(-1).tostring('yyyy-MM-dd'))} |
remove-azurermsnapshot -force
}
The name of the snapshot is formatted like this with the below code: Testvm---2018-09-20
$timestamp = Get-Date -f ---yyyy-MM-dd
$snapshotName = $vmInfo.Name + $timestamp
So I think my problem area is this part
?{($_.TimeCreated).ToString('yyyy-MM-dd') -lt ([datetime]::Today.AddDays(-1).tostring('yyyy-MM-dd'))} | remove-azurermsnapshot -force
-lt
, this isn't going to work in the way you want. Try removing.ToString()
and you might get a better result comparing the nativedatetime
objects instead :)?{($_.TimeCreated) -lt ([datetime]::Today.AddDays(-1))} | remove-azurermsnapshot -force
$rg = 'snapshots' $snapshotnames = (Get-AzureRmSnapshot -ResourceGroupName $rg).name foreach($snapname in $snapshotnames) { Get-AzureRmSnapshot -ResourceGroupName $rg -SnapshotName $snapname |?{($_.TimeCreated) -lt ([datetime]::Today.AddDays(-1))} | remove-azurermsnapshot -force | remove-azurermsnapshot -force }