Skip to content

Instantly share code, notes, and snippets.

@rayterrill
Created September 21, 2016 21:43
Show Gist options
  • Save rayterrill/418b655e76161548e4824a11d1c2f2e2 to your computer and use it in GitHub Desktop.
Save rayterrill/418b655e76161548e4824a11d1c2f2e2 to your computer and use it in GitHub Desktop.
Advance Windows Domain Machine Snapshots to Avoid Machine Account Expiration Issues when Reverting to Snapshot
& "C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1"
<#
We have several VMs we use for repetitive testing activities, and frequently need to revert them to a "known good"
snapshot in order to undo changes. If we forget to do this in the default 30 day machine account expiration window,
however, we need to work with our SYSADMIN team to join these back to the domain post-revert.
This script reverts machines to known good snapshots using the Name property of the snapshots. Not the most elegant
thing in the world (I'd love to see if others have better/slicker ideas!), but it should work for us.
#>
Connect-VIServer -Server MYVSPHERESERVER.MYDOMAIN.COM
function New-VMSnapshot($vm,$location) {
$username = [Environment]::UserName
$today = Get-Date -Format M.d.yyyy
New-Snapshot -Name "[BASE_REVERTABLE]-$($username)-$($today)" -Description "BASE SNAPSHOT" -Memory -Quiesce -VM(Get-VM -Name $vm -Location $location)
}
function Revert-VMToBaseSnapshot($vm, $snapshot) {
Set-VM -VM $vm -SnapShot $snapshot -Confirm:$false
}
function Delete-VMSnapshot($snapshot) {
Remove-Snapshot -Snapshot $snapshot -Confirm:$false
}
#threshold date to find vms older than 20 days
$thresholdDate = (Get-Date).AddDays(-20)
#find any machines with snapshots tagged with *BASE_REVERTABLE* (meaning we're ok to revert them automatically) older than threshold date days
$dataCenters = Get-DataCenter
foreach ($d in $dataCenters) {
$snapshots = Get-VM -Location $d.Name | Get-Snapshot | Where-Object {$_.Name -Like "*BASE_REVERTABLE*"}
foreach ($s in $snapshots) {
$nameExploded = $s.Name.split('-')
$username = $nameExploded[1]
$date = Get-Date $nameExploded[2]
if ($date -lt $thresholdDate) {
Write-Host "Need to redo snapshot for VM $($s.VM.Name)!"
Write-Host "`tReverting to BASE SNAPSHOT..."
Revert-VMToBaseSnapshot -VM $s.VM.Name -Snapshot $s
Write-Host "`tSleeping 60 seconds to make sure the VM comes back up."
Start-Sleep 60
Write-Host "`tTaking a new snapshot..."
New-VMSnapshot -VM $s.VM.Name -Location $d.Name
Write-Host "`tDeleting the previous snapshot..."
Delete-VMSnapshot -Snapshot $s
} else {
Write-Host "Snapshot is still good for VM $($s.VM.Name)."
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment