Anda di halaman 1dari 7

#=============================================================================== # # FILE: SnapshotReminder.ps1 # # USAGE: ./test.

sh # # DESCRIPTION: VMware vSphere/vCenter/ESX/ESXi snapshot creator notifier # # OPTIONS: --# REQUIREMENTS: --# BUGS: --# NOTES: It emails a list of snapshots more then 2 days old to the # creator(s) as well as a summary list of all sn apshots more # more then 2 days old to the specified admins. # Script History and Credits # - SnapReminder V1.0 By Virtu-Al - http://virtu -al.net # modified by Carl Chipman # heavily reworked by David Dionne # AUTHOR: David Dionne (dtdionne@hotmail.com) # COMPANY: # VERSION: 1.0 # CREATED: 06/ 6/2012 8:58:22 AM CDT # REVISION: --#=============================================================================== if (-not (Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) { Add-PSSnapin VMware.VimAutomation.Core } $tday = get-date -uformat "%a_%m_%d_%y" $strFrom = "" $mm = "" $VISERVER = "" $VMwareAdminGroup = "" #$VMwareAdminGroup = "Administrators" $unFilter = "_" $default_mail_tgt = "" $unknown_mail_tgt = "" $smtpServer = "" $strOutDir = "C:\scripts\$tday\" $uStrOutFile = "$($usr)_snapshot_notify_list_for_$($tday).html" $sStrOutFile = "summery_snapshot_notify_list_for_$($tday).html" function Get-LocalGroupMembers() { $groupName = "$VMwareAdminGroup" $lines = net localgroup $groupName $found = $false $peepee = $true $i = 0 while ( $peepee ) { if ( $lines[$i] -match "^----" ) { $i++ $found = $true } while ( -not $lines[$i].StartsWith("The command completed") -and

($found)) { if ( $lines[$i].Contains("$unFilter") -or $lines[$i] -ma tch "Administrator") { $i++ } else { $lines[$i] $i++ $peepee = $false } } $i++ } } 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) { # The name of the guest $guestName = $snap.VM # Windowsize of the Task collector $tasknumber = 999 $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(-360)) $filter.Time.timeType = "startedTime" $filter.State = "success" $filter.Entity = New-Object VMware.Vim.TaskFilterSpecByEntity $filter.Entity.recursion = "self" $filter.Entity.entity = (Get-Vm -Name $snap.VM.Name).Extensiondata.MoRef $collectionImpl = Get-View ($taskMgr.CreateCollectorForTasks($filter))

$collection = $collectionImpl.ReadNextTasks($tasknumber) while($collection -ne $null){ $collection | where {$_.DescriptionId -eq "VirtualMachine.create Snapshot" -and $_.State -eq "success" -and $_.EntityName -eq $guestName} | %{ $row = New-Object PsObject $row | Add-Member -MemberType NoteProperty -Name User -Value $_.Reas on.UserName $vm = Get-View $_.Entity $snapshot = Get-SnapshotTree $vm.Snapshot.RootSnapshotList $_.Result if ( $snapshot -ne $null) { $key = $_.EntityName + "&" + ($snapshot.CreateTime.ToLocalTime() .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.ToLocalTime().ToString()) if($report.ContainsKey($key)) { $_ | Add-Member -MemberType NoteProperty -Name Creator -Value $repor t[$key].User # write-host $report[$key].User is creator of $key } $_ } $snapshotsExtra } #_______________________________________________________________________________ __________________________________________# Connect-VIServer -Server $VISERVER $myCol = @() $sMyCol = @() $eUsers = @() if (!(Test-Path $stroutdir)) { mkdir $strOutDir } # Builds main Object $Users = Get-VM | Get-Snapshot | Where {$_.Created -lt ((Get-Date).AddDays(-2))} | foreach { Get-SnapshotExtra $_ } | Group-Object -property Creator #$Users = Get-VM | Get-Snapshot | foreach { Get-SnapshotExtra $_ } | Group-Objec t -property Creator $VCAdmins = Get-LocalGroupMembers $a = 0 $b = @() while ( $VCAdmins.Count -gt $a ) {

$b += $VCAdmins[$a] + $mm $a++ } $OFS = ', ' $default_mail_target = "$b" $unknown_mail_tgt = "$VCAdmins" rv OFS $users_num = $Users.count $Loop = 0 while ($Loop -lt $Users_num) { $U = $Users["$loop"] $uc = $Users["$loop"].Count $count = 0 while ($count -lt $uc) { $G = $u.Group["$count"] if ($count -eq 0) { if ($Users["$loop"].Name -eq "" -or $Users[$loop].Name eq "Unknown") { $usr = "Unknown" $default_mail_tgt = $unknown_mail_tgt } else { $usr = $users["$loop"].Name $default_mail_tgt = "$usr$mm" } } $myObj = "" | Select-Object VM, Snapshot, Created, CreatedBy, Em ailedTo, Note $myObj.VM = $G.VM.Name $myObj.Snapshot = $G.Name $myObj.Created = $G.Created $myObj.CreatedBy = $usr $myObj.EmailedTo = "$default_mail_tgt" $myObj.Note = $G.Note $myCol += $myObj $count++ } if ($usr -ne "unknown") { $eUsers += $usr } nv "Col_$usr" $myCol $sMyCol += $myCol # -------------- Unknown Creator Snapshot File Setup---------------------------if ($usr -eq "Unknown") { # Output File $uStrOutFile = "$($usr)_snapshot_notify_list_for_$($tday).html" $uStrFile = "$strOutDir$uStrOutFile"

HTML/CSS style for the output file $head = "<style>" $head = $head + "BODY{background-color:white;}" $head = $head + "TABLE{border-width: 1px;border-style: solid;bor der-color: black;border-collapse: collapse;}" $head = $head + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:thistle}" $head = $head + "TD{border-width: 1px;padding-left: 10px;padding -right: 10px;border-style: solid;border-color: black;background-color:PaleGolden rod}" $head = $head + "</style>" $default_mail_tgt = $default_mail_target $strTo = "$default_mail_tgt" $strSubject = ?$($usr)'s Snapshot Reminder - ? + (get-date -Disp layHint date) $strBody = "This is a list of orphaned Snapshots over 2 days old . If you recall creating any of them and no longer need them, please delete the m." $strMail = "<H2><u>" + $strSubject + "</u></H2>" + "<H5>" + $str Body + "</H5>" $myCol | Sort-Object VM | ConvertTo-HTML -Head $head -Body $strM ail | Out-File $uStrFile } # -------------- Username Snapshot File Setup----------------------------else { # Output File $uStrOutFile = "$($usr)_snapshot_notify_list_for_$($tday).html" $uStrFile = "$strOutDir$uStrOutFile" # HTML/CSS style for the output file $head = "<style>" $head = $head + "BODY{background-color:white;}" $head = $head + "TABLE{border-width: 1px;border-style: solid;bor der-color: black;border-collapse: collapse;}" $head = $head + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:thistle}" $head = $head + "TD{border-width: 1px;padding-left: 10px;padding -right: 10px;border-style: solid;border-color: black;background-color:PaleGolden rod}" $head = $head + "</style>" $strTo = "$usr$mm" $strSubject = ?$($usr)'s Snapshot Reminder - ? + (get-date -Disp layHint date) $strBody = "This is the list of your Snapshots" $strMail = "<H2><u>" + $strSubject + "</u></H2>" + "<H5>" + $str Body + "</H5>" $myCol | Sort-Object VM | ConvertTo-HTML -Head $head -Body $strM ail | Out-File $uStrFile } $myCol = @() $Loop++ } # -------------- Summary File Setup----------------------------# Output File $sStrFile = "$strOutDir$sStrOutFile"

#$strOutFile = "C:\Scripts\summery_snapshot_notify_list_for_$($tday).htm" # HTML/CSS style for the output file $head = "<style>" $head = $head + "BODY{background-color:white;}" $head = $head + "TABLE{border-width: 1px;border-style: solid;border-color: black ;border-collapse: collapse;}" $head = $head + "TH{border-width: 1px;padding: 0px;border-style: solid;border-co lor: black;background-color:thistle}" $head = $head + "TD{border-width: 1px;padding-left: 10px;padding-right: 10px;bor der-style: solid;border-color: black;background-color:PaleGoldenrod}" $head = $head + "</style>" $strTo = $default_mail_target $strSubject = ?Complete list of Snapshots over 2 days old - ? + (get-date -Displ ayHint date) $strBody = "Here is the complete list of Snapshots and their Creators" $strMail = "<H2><u>" + $strSubject + "</u></H2>" + "<H5>" + $strBody + "</H5>" $sMyCol | Sort-Object VM | ConvertTo-HTML -Head $head -Body $strMail | Out-File $sStrFile # -------------- Email ----------------------------$emailUsers = @() $match = $false foreach ($j in $VCAdmins) { $match = $false foreach ($i in $eUsers) { if ($i -ne $j) { } else { $match = $true } } if (!$match) { $emailUsers += $j } } foreach ($p in $eUsers) { $emailUsers += $p } foreach ($r in $emailUsers) { $usr = $r $strTo = "$usr$mm" $uEmailOutFile = "$($usr).html" $uEmailFile = "$strOutDir$uEmailOutFile" $uStrOutFile = "$($usr)_snapshot_notify_list_for_$($tday).html" $uStrFile = "$strOutDir$uStrOutFile" if ($eUsers -contains $usr) { cat $uStrFile > $uEmailFile

} if ($VCAdmins -contains $usr) { $userid = $usr $usr = "Unknown" $uStrOutFile = "$($usr)_snapshot_notify_list_for_$($tday).html" $uStrFile = "$strOutDir$uStrOutFile" cat $uStrFile >> $uEmailFile cat $sStrFile >> $uEmailFile $usr = $userid } $msg = new-object Net.Mail.MailMessage $att = new-object Net.Mail.Attachment($uEmailFile) #_____________________________ if (!$enableSSL -or !$implicitSSL) { $smtp = new-object Net.Mail.SmtpClient($smtpServer, $serverPort) $smtp.EnableSsl = $enableSSL if ($enableSSL) { # $credentials = [Net.NetworkCredential](Get-Credential) # $smtp.UseDefaultCredentials = $false; $smtp.Credentials=New-Object System.Net.NetworkCredential($useri d,$userpwd) $smtp.Credentials = $creds } $msg.From = $strFrom $msg.To.Add($strTo) $msg.Subject = $strSubject $msg.IsBodyHtml = 1 $msg.Body = Get-Content $sStrFile $msg.Attachments.Add($att) Adding a Bell Icon for Outlook users $msg.Headers.Add("message-id", "<3BD50098E401463AA228377848493927-1>")

Write-Output "Attempting to send email from Function Main for Complete L ist to $strTo..." try { $smtp.Send($msg) Write-Output "Message sent." } catch { Write-Error $_ Write-Output "Message send failure." } } } $att.Dispose();

Anda mungkin juga menyukai