Hi Guys I'm really stuck here and I'm a real noob at scripts.
I basically need to generate a daily report of VM with snapshots older than 3 days and send to my email aaddress in HTML format.
I need to add the creator of the snapshot, the VM name, the snapshot name, date and time in DD/MM/YYYY and 24hour time.
This is where I'm at so far. I would really appreciate some help on this.
function Get-SnapshotTree{
param($tree, $target)
$found = $null
foreach($elem in $tree){
if($elem.Snapshot.Value -eq $target.Value){
$found = $elem
continue
}
}
if($found -eq $null -and $elem.ChildSnapshotList -ne $null){
$found = Get-SnapshotTree $elem.ChildSnapshotList $target
}
return $found
}
function Get-SnapshotExtra ($snap){
#$daysBack = 5 # How many days back from now
$guestName = $snap.VM # The name of the guest
$tasknumber = 999 # Windowsize of the Task collector
#$serviceInstance = get-view ServiceInstance
$taskMgr = Get-View TaskManager
# Create hash table. Each entry is a create snapshot task
$report = @{}
$filter = New-Object VMware.Vim.TaskFilterSpec
$filter.Time = New-Object VMware.Vim.TaskFilterSpecByTime
$filter.Time.beginTime = (($snap.Created).AddSeconds(-5))
$filter.Time.timeType = "startedTime"
$collectionImpl = Get-View ($taskMgr.CreateCollectorForTasks($filter))
$dummy = $collectionImpl.RewindCollector
$collection = $collectionImpl.ReadNextTasks($tasknumber)
while($collection -ne $null){
$collection | where {$_.DescriptionId -eq "VirtualMachine.createSnapshot" -and $_.State -eq "success" -and $_.EntityName -eq $guestName} | %{
$row = New-Object PsObject
$row | Add-Member -MemberType NoteProperty -Name User -Value $_.Reason.UserName
$vm = Get-View $_.Entity
$snapshot = Get-SnapshotTree $vm.Snapshot.RootSnapshotList $_.Result
if ($snapshot.CreateTime -eq $null) {
$key = $_.EntityName + "&" + "unknown"
} else {
$key = $_.EntityName + "&" + ($snapshot.CreateTime.ToString())
}
$report[$key] = $row
}
$collection = $collectionImpl.ReadNextTasks($tasknumber)
}
$collectionImpl.DestroyCollector()
# Get the guest's snapshots and add the user
$snapshotsExtra = $snap | % {
$key = $_.vm.Name + "&" + ($_.Created.ToString())
if($report.ContainsKey($key)){
$_ | Add-Member -MemberType NoteProperty -Name Creator -Value $report[$key].User
}
$_
}
$snapshotsExtra
}
$Snapshots = Get-VM | Get-Snapshot | Where {$_.Created -lt ((Get-Date).AddDays(-3))}
$mySnaps = @()
foreach ($snap in $Snapshots){
$SnapshotInfo = Get-SnapshotExtra $snap
$mySnaps += $SnapshotInfo
}
$mySnaps | Select VM, Name, Creator, Description
Nicholas