Friday, January 29, 2016

Zerohorizon.net Browser Redirect Trojan

As I sit here I am frequently being annoyed by a nasty little redirect Trojan that "someone" who used my computer picked up.  I am extremely careful, and very cautious about who uses my PC.  Each of my kids has their own PC, as does my wife.  No one outside of my immediate family uses my PC.  So that leaves either myself or my wife.

It doesn't really matter and I'm not blaming anyone.  In fact my every-day operating system is Centos Linux so this is little more than an occasional annoyance for me.  It doesn't help that I'm so irritated with Microsoft these days that I only use Windows when and IF I have to.  That boils down to about three programs.  Everything else is on Linux.

The Linux side works fine, it's just this Swiss-Cheese OS named Windows that's any issue.  Anyway, I could go on for hours about the various issues I have with Microsoft, but I digress.

So I am documenting what I have found so that if anyone else with this issue can benefit from it, so much the better.

This Trojan is sneaky.  You can search Google all day long and mostly what you find are very randomly named web sites that appear to all be slight variations on the same destination.  Where you wind up is some site that wants to sell you "their" virus removal tool, something called "SpyHunter".
I have no idea if this product is legitimate or not but I recommend that anyone reading this stay away from it.  The fact that 40 or 50 oddly named web sites, each with a slightly varied content, all suggest you use this product makes me very suspicious.

Almost all of these supposed "removal" sites run you through removing installed "bad" programs, "bad" browser extension, and editing the system registry.  Trouble is these steps don't help and don't accomplish anything.  The final step is "oh, none of this worked, try buying our tool...".  Yeah, right...

Also, why have none of the major anti-virus program authors jumped on this?  The fact that they are saying nothing again makes me very suspicious.  This seems to be a prety common infection, there are loads of Google hits when you look up zerohorizon.net.

I've scanned my system with Comodo, Avast, Kaspersky, and also scanned the Windows OS drive while Linux was running (the only REAL way to scan Windows for viruses), and nothing has been found.  Very odd.

This seems to primarily affect the Google Chrome browser (note that as far as I can tell Google has said nothing about this either), but Firefox, and IE have both been reported to be affected.

OK, enough soap box, time for details.

This Trojan is a browser redirect.  At random times it pops up new tabs or windows that load one of a small list of sites.  These sites are all adware sites or sites with fake pages that try to fool you into clicking on links which will likely install other nasty things.  It may also be doing any number of other things, there is really no way to tell without reverse engineering it.  Before that can be done it needs to be located.  The list of sites it uses (so far) is below.  They all seem to eventually bounce through www.buy-targeted-traffic.com and if that doesn't sound like a shady site I don't know what does:

  • buy-targeted-traffic.com
  • orion.zerohorizon.net
  • oziris.zerohorizon.net
  • zerohorizon.net
  • onclicktop.com
  • fugdownload164.com
  • fugdownload173.com
  • ptp24.com
  • cdn.shorte.st
  • shorte.st
  • bundleworldbits.com
  • putono5.com
  • cdn.putono5.com
  • d.putono5.com
  • a.putono5.com
(Damn! Within 15 minutes of posting this I found 2 more sites to add...)
  • adspserving.com
  • xl415.com

  • truequotes.org       (added 1-31-16)

I will add to that list as I find more entries.  These sites were found either via a direct pop-up, or by  reviewing the source code of the pop-up pages.  By the way, to view the HTML code to find these site just right mouse click the blank web page in the browser and select "view source".  Most entries will be bad but some are ok such as "http://www.w3.org" which is the group that sets web code standards.  Look for entries such as "http://<whateversite.com>", these are the "bad" sites it's trying to direct you to.

I have so far not been able to determine the method this thing uses to load.  It appears to be pretty stealthy.  I have some experience with PC forensics and to date I have yet to locate the root cause.  Many other posts seem to indicate a bogus browser plugin is the culprit.  I do occasionally use some but nothing I would be wary of.

In any case the best thing so far is placing entries for each site in the local PC hosts file.  This file is the first location the computer uses when it tries to identify the TCP/IP address of a site.  For those unfamiliar with this, the computer connects to the site IP address, not the site name, so it must translate between the two first.  Normally this is done automatically via DNS, but if a hosts file exists those entries take precedence.   In fact many viruses and Trojans use this file to redirect you to bad sites.

The hosts file is located here:  C:\Windows\System32\Drivers\Etc\hosts and no, there is no extension such as ".txt" on it.  In fact you may not be able to see the file without making a few adjustments in the Windows file explorer (look for info at Google on viewing hidden files).

By adding these entries the browser pop-up still occurs, but it cannot find the sites it wants and so does nothing but load a blank page.  This "should" have the effect of neutering the Trojan.  This won't stop it, or remove it, but it seems to slow it down.  Below is what the file will look like after editing.  This is a copy-&-paste of my own file:

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
# 127.0.0.1       localhost
# ::1             localhost
127.0.0.1  buy-targeted-traffic.com
127.0.0.1  orion.zerohorizon.net
127.0.0.1  oziris.zerohorizon.net
127.0.0.1  zerohorizon.net
127.0.0.1  onclicktop.com
127.0.0.1  fugdownload164.com
127.0.0.1  fugdownload173.com
127.0.0.1  ptp24.com
127.0.0.1  cdn.shorte.st
127.0.0.1  shorte.st
127.0.0.1  bundleworldbits.com
127.0.0.1  putono5.com
127.0.0.1  cdn.putono5.com
127.0.0.1  d.putono5.com
127.0.0.1  a.putono5.com
127.0.0.1 adspserving.com
127.0.0.1 xl415.com
127.0.0.1 truequotes.org

The entries prefixed with "127.0.0.1" cause a lookup of any of those sites to be redirected to "loopback" which is a local test address that goes no where.

Again, this is a "band-aid" and will not stop the Trojan.

My suspicion is that when this thing was installed it added a hook into the operating system at some non-common area.  It would appear to be a scheduled task of some sort but so far none of the tasks seem out of order.  Windows 7, 8, and 10 include a plethora of schedules tasks that do a myriad of things.  So many that it's hard to figure out what belongs.  There also may be settings added to the browser or system registry but so far I've identified nothing.  More than like this is running as a scheduled task somewhere due to the regular occurrence of it.

As I find new info I'll list it here.  If anyone reading this has comments or additions please leave a comment.  I would very much like to kill this thing without reinstalling Windows.  It's annoying more than anything and since I usually work in Linus it's even more annoying that I have to deal with it the few times I run Windows.

More later....


Dang.... Sorry I can't seem to post replies to comments.  Not sure why.   The comment about auditing is a good one.  I set it up on the "...\Local\Temp" folder and found Chrome.exe to be the culprit.  Trouble is that doesn't tell me what caused Chrome to execute a new instance.  I think I'll audit the exe itself and see what I get...


Update 02-21-16
Since I've mostly switch to Linux this issue hasn't been on the top of my priority list.  Either way I did make some headroom.  What I did was adjust the Windows startup to see what could be turned off to stop this.  I'm down to three items still shut off.  First is the Windows sidebar at "c:\program files\windows sidebar\sidebar.exe".  Next is the Windows error reporting server wer.exe at "c:\programdata\microsoft\windows\wer\wer.exe".  Lastly the Comodo "GeekBuddy" service, which I just read is a huge security risk anyway.  I use Comodo for Antivirus.  So far there have been NO new occurrences.  I would be curious to see if anyone else sees the same effect.

Update 03-11-16
Still cant reply to comments for some reason.  In response to the third comment...  Very interesting.  What files were involved and what did you do to identify and fix it?  The more detail we can post the more it might help someone else.  I'm planning to reinstall Windows (something I've done way too many times in my life) since It will only be left on my system for the things I absolutely can't run under Linux.  After that I expect the issue will be a moot point.

Update 05-28-16
In response to the May 19th post...  I would love to be able to test this but I have been exclusively running Linux for some time now. I never noticed any bogus accounts on my system and being a professional sysadmin I tend to have a pretty intimate knowledge of my systems.  Still this could be a valuable check should it find something.  Best of luck.

Update 07-27-16
I haven't suffered from this beasties sting for a number of months now.  Since switching over exclusively to Linux I've seen nothing.  I'm pretty sure I now know why.  I'm surprised I hadn't hit on this before due to the obvious symptoms.  I feel like an audience member watching a magic act and never noticing the assistant in the audience feeding the magician clues.

Like I said before... scheduled tasks...  the trick here is "trigger start tasks" which are a new feature with Windows 7 and later versions of the OS.  Basically Microsoft has once again given the bad guys a wonderful tool to pick our pockets.  True, it's a great feature, if you use your powers for good.  Trouble is when powerful things are placed in the hands of idiots it doesn't take long for them to become corrupted.  Heck I've used them at work for things myself.

Trigger start tasks are those that only fire off when a specific action is detected on the PC.  This could be logon, logoff, system idle, or... a mouse click in a certain place, like say a browser window....  See where I'm going here.  This is a well know tactic of adware and malware authors.  See this article for details: https://blog.malwarebytes.com/cybercrime/2015/03/scheduled-tasks/

The hard part is that Microsoft pretty much runs Windows on these tasks and they include a LOT of them out of the box.  Did you think the OS detected you inserting a DVD or memory key by magic?  Nope, trigger start tasks.

So, why you may ask, am I still blabbering about these PUPs (Potentially Unwanted Programs) again?  Well I initially got nailed by some damn Chrome extension, god only knows which.  I, like many of you sync my settings between browsers, and now my work browser running on Windows has dutifully synced whatever extension came with this crap and so once again I'm trying to rid my life of it.

I'm working on a few things to clean this up like PowerShell scripts to list and purge the trigger tasks.  The new task scheduler store task definitions as XML files with a ".JOB" extension so you can search for them and scan their contents.  Once I get something concrete I'll post it here.



Tuesday, January 19, 2016

Tegile Zebi Storage and PowerShell

For any of you that use SAN products from Tegile, they have had a REST API available since 2014 to access the SAN controllers, but it's never been really useful.  They tell me that this will be changing and they will actually have some commandlets available soon.

The user guide for the API is written from a PERL viewpoint and all the examples are in PERL.  That's great except that I use very little PERL in my day-to-day life.

I decided to try and convert to PowerShell and see what I could see.  There are a number of examples of using REST API via PowerShell around the net.  After trying variations of a number of them I would up with the code below.  It will pull out the Zebi version information from the array.

It's still very limited as to what you can do, but it's a start.  The full list of commands available are in the REST API user guide over at the Tegile support site.

This script is functional but not pretty.  It was basically just proving that it worked.



Clear-Host

$Username = Read-Host "Enter the username"
$Password = Read-Host "Enter the password"
$EncodedAuthorization = [System.Text.Encoding]::UTF8.GetBytes($Username + ':' + $Password)
$EncodedPassword = [System.Convert]::ToBase64String($EncodedAuthorization)
$IP = Read-Host "Enter the IP Address"
$BaseURL = 'https://' + $IP
$Headers = @{"Authorization"="Basic $($EncodedPassword)"}

$ResourceURL = "/zebi/api/v1/listShares"                      #--[ Remove the body option if using this ]--
$Body = '[["ZEBI_API_VERSION","ZEBI_APPLIANCE_VERSION","ZEBI_API_MINOR_VERSION","ZEBI_APPLIANCE_MODEL","ZEBI_GUI_VERSION"]]'     #--[ Edit this as required ]--

$ResourceURL = "/zebi/api/v1/listProjects"                      #--[ Remove the body option if using this ]--

$ResourceURL = "/zebi/api/v1/listSystemProperties"            #--[ Edit this as required ]--
$Body = '[["ZEBI_API_VERSION","ZEBI_APPLIANCE_VERSION","ZEBI_API_MINOR_VERSION","ZEBI_APPLIANCE_MODEL","ZEBI_GUI_VERSION"]]'     #--[ Edit this as required ]--

$URI = $BaseURL + $ResourceURL


Try
     {
     $Result = Invoke-RestMethod -Uri $URI -Method post -Headers $Headers -ContentType "application/json; charset=utf-8" -ErrorAction Stop -Body $Body
     }
Catch
     {
    $ErrorMessage = $_.Exception.Message
    $FailedItem = $_.Exception.ItemName
    write-host "Error Message : "$ErrorMessage -ForegroundColor yellow
    write-host "Failed Item : "$FailedItem -ForegroundColor yellow
     }


write-host `n"     URL: "$URI -ForegroundColor Yellow
write-host " API Ver: "$Result[0] -ForegroundColor Yellow
write-host "Zebi Ver: "$Result[1] -ForegroundColor Yellow


$Result

Friday, September 18, 2015

Great balls o' fire...

For anyone reading this that's looking for updated information on our situation, everything is good.

For those curious, I live in the Sierra foothills in California.  The Butte fire which started a week ago just ravaged my area.  70,000 acres burned, 360 homes destroyed, 2 fatalities.

The fire stopped about 500 yards from my home.  We were EXTREMELY lucky.  Seems to be a freak effect of the area we live in that caused the fire to shift and detour around our street.  All the houses on our street are fine, no damage, and just across the creek are foundations with no houses.  Damn scary.

The roads are still closed due to downed power poles and lines.  I understand the need to make things safe, and I am amazed at the herculean effect PG&E is taking to get power back in place,  but I am really getting tired of people telling that "the roads are still closed" just to watch the "special" people drive right down them.  Those would include anyone with any sort of "official" looking vehicle, regardless of who they may be.  And no, that doesn't include us.

Many thanks to the hundreds of fire fighters who focused on saving homes.  They did a phenomenal job and many homes were saved, mine among them.  Tragically two hold-outs lost their lives when they refused to leave when evacuations were called.  I do promise to not complain for the next year about the "special fire tax" being imposed on us due to gross mismanagement at CalFire, or state government, or whoever screwed that up, but after that I reserve the right to complain again.

Here some pics I took to give you an idea.  I left them full size so they are pretty big.

These are views from the house we stayed at while evacuated.  We got evacuated from there twice as well.






Yesterday I was able to get back home for the first time via some nasty logging roads to get the fridge cleaned out and disinfected.  Smelled pretty nasty.  The main road is still closed to it will be hit and miss on getting normal access.  For now looks like the 1.5 hour trip down the logging road.  That road is actually pretty scary.  There are some compounds back there miles from anything with high chain link fences with razor wire.  Every time I drive there I hear the banjos from Deliverance playing in my head...

I took this one from my porch.  You can see how close the fire got through the trees.  The hillside is all burned as well as the trees across the creek.



Tuesday, September 1, 2015

VMware Datastore Utilization Tracker

I like to keep an arsenal of automated scripts that run as scheduled tasks to report on the status of various things I manage.  Here is one of those.

Our virtualization environment uses a SAN backend as most do.  We run exclusively in NFS (NAS) mode.  This has numerous advantages (an explanation of which is outside the scope of this post).  I like to keep a rough idea of the gains and losses of each NFS share on a daily basis.

I run the following script automatically each day and it emails me the details of the gains or losses due to systems being added or removed.  I included a "noupdate" option that allows testing without processing the files.  That way you can rerun using the current file again and again for testing.

Results are very basic and color coded for gain/loss.  The raw dump files are stored in the script folder.  I have another process I use to import them into Excel and graph them over time.  If I get a chance I'll post that as well.

NOTE: This NOT the current version.  I am keeping current versions on the MS PowerShell Gallery at: https://www.powershellgallery.com/profiles/Kcmjr/.

<#======================================================================================
         File Name : Datastore-Tracker.ps1
   Original Author : Kenneth C. Mazie (kcmjr AT kcmjr DOT com)
                   :
       Description : Tracks SAN datastores over time.  Emails a daily report on changes.
                   :
             Notes : Normal operation is with no command line options.  Basic logs are written to C:\Scripts
                   : Optional argument: -Console $true (defaults to false)
                   :                    -NoUpdate $true (runs with current files and doesnt replace them for debugging)
                   :
          Warnings : The script is coded to switch colors between 2 vCenters.  Adjust as
                   : needed below where commented if you use more or less.
                   :  
             Legal : Public Domain. Modify and redistribute freely. No rights reserved.
                   : SCRIPT PROVIDED "AS IS" WITHOUT WARRANTIES OR GUARANTEES OF
                   : ANY KIND. USE AT YOUR OWN RISK. NO TECHNICAL SUPPORT PROVIDED.
                   :
           Credits : Code snippets and/or ideas came from many sources including but
                   :   not limited to the following:
                   : Based on "Track Datastore Space script" Created by Hugo Peeters of www.peetersonline.nl
                   :
    Last Update by : Kenneth C. Mazie
   Version History : v1.0 - 09-16-14 - Original
    Change History : v1.1 - 08-28-15 - Edited to allow color coding of HTML output    
                   :
#=======================================================================================#>
#requires -version 3.0

Param(
     [bool]$Console = $False,
     [bool]$NoUpdate = $False
     )
If ($Console){$Script:Console = $true}

#--[ Uncomment to programatically hide the console ]--
#Add-Type -Name Window -Namespace Console -MemberDefinition '
#[DllImport("Kernel32.dll")]
#public static extern IntPtr GetConsoleWindow();
#
#[DllImport("user32.dll")]
#public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
#'
#$Script:consolePtr = [Console.Window]::GetConsoleWindow()
#[Console.Window]::ShowWindow($Script:consolePtr, 0)

Clear-host
$Script:Body = ""  
$ErrorActionPreference = "silentlycontinue"

#--[ Excel Non-Interactive Fix ]------------------------------------------------
If (!(Test-path -Path "C:\Windows\System32\config\systemprofile\Desktop")){New-Item -Type Directory -Name "C:\Windows\System32\config\systemprofile\Desktop"}
If (!(Test-path -Path "C:\Windows\SysWOW64\config\systemprofile\Desktop")){New-Item -Type Directory -Name "C:\Windows\SysWOW64\config\systemprofile\Desktop"}
#--[ Excel will crash when run non-interactively via a scheduled task if these folders don't exist ]--

#-------------------------------------------------------------------------------
#--[ NOTE: The script is set up for two vCenters.  Adjust the coloring below if you have more or less ]--
$Script:vCenters = @("vCenter1","vCenter2")  
#-------------------------------------------------------------------------------
If ($Script:NoUpdate){
       $Script:CurrentFile = $Script:PSScriptRoot+'\Temp_Current.xml'
       $Script:PreviousFile = $Script:PSScriptRoot+'\Datastores_Previous.xml'
       $Script:DifferenceFile = $Script:PSScriptRoot+'\Temp_Difference.txt'
}Else{
       $Script:CurrentFile = $Script:PSScriptRoot+'\Datastores_Current.xml'
       $Script:PreviousFile = $Script:PSScriptRoot+'\Datastores_Previous.xml'
       $Script:DifferenceFile = $Script:PSScriptRoot+'\Datastores_Difference.txt'
}
If (Test-Path $Script:DifferenceFile) {rm $Script:DifferenceFile -Confirm:$false -Force}
If (!(Get-PSSnapin | ? {$_.name -like “vmware.vimautomation.core”})) {Add-PSSnapin vmware.vimautomation.core}
$Script:Digits = 2
$Script:From = "DailyRepoprts@mydomain.com"                                     #--[ Who the email is being sent by ]--
$Script:UserName = "mydomain\username"                                          #--[ The user to connect to vCenter with ]--
$Script:Password = "userpassword"                                               #--[ That users password ]--
$Script:EmailTargets = "user1.domain.com, user2.domain.com"                     #--[ a comma seperated list of email recipients ]--
$Script:SMTPServer = "HostName.domain.int"                                      #--[ what SMTP server to use ]--

Function SendEmail ($Script:OutBody){                                           #--[ Email settings ]--
       $Script:HTML = $true
       $Script:Email = new-object System.Net.Mail.MailMessage
       $Script:Email.From = $Script:From
       $Script:Email.To.Add($Script:EmailTargets)
       $Script:Email.Subject = "SAN Daily Utilization Status"
       $Script:Email.IsBodyHtml = $true
       $Script:Email.Body = $Script:ReportBody
       $Script:smtp = new-object System.Net.Mail.SmtpClient($Script:SMTPServer)
       $Script:smtp.Send($Script:Email)
}

#--[ Add header to html log file ]----------------------------------------------
$Script:ReportBody = @()
$Script:ReportBody += '
<style type="text/css">
       table.myTable { border:5px solid black;border-collapse:collapse; }
    table.myTable td { border:2px solid black;padding:5px}
       table.myTable th { border:2px solid black;padding:5px;background: #949494 }
       table.bottomBorder { border-collapse:collapse; }
       table.bottomBorder td, table.bottomBorder th { border-bottom:1px dotted black;padding:5px; }
</style>
<left><h1>&nbsp;&nbsp;&nbsp;- SAN Volume Utilization Report -</h1></left>
The following report displays the current SAN volume usage and the percent of<br>
change from yesterdays usage.  The raw data files are retained with the script<br>
for use in long term utilization tracking purposes.<br><br>'
$Script:ReportBody += '<table class="myTable"><tr><th>vCenter</th><th>Volume Name</th><th>Percent Free</th><th>Difference</th></tr>'

If (!(Test-Path "$PSScriptRoot\creds.txt")){
  $Script:Credential = Get-Credential
  $Script:Credential.Password | ConvertFrom-SecureString | Set-Content "$PSScriptRoot\creds.txt"
}

#--[ Use if you need to use a credential file, otherwise current creds are used ]--
#$Encrypted = Get-Content "$Folder\creds.txt" | ConvertTo-SecureString
#$Credential = New-Object System.Management.Automation.PsCredential($Username, $Encrypted)
#$LogFileName = "SAN-Vol_{0:MM-dd-yyyy_mm}_Stats.log" -f (Get-Date)
$Script:myColCurrent = @()                                                       #--[ Create an array to hold the output ]--

ForEach ($Script:VIServer in $Script:vCenters){
       If ($Script:Console){Write-Host "`r`nProcessing: $Script:VIServer" -ForegroundColor Cyan}
       $Script:VC = Connect-VIServer -Server $Script:VIServer -user $Script:UserName -pass $Script:Password #-Credential $Script:Credential #--[ Connect to Virtual Center ]--
       $Script:datastores = Get-Datastore | Sort-Object Name | Select -Unique            #--[ Get all datastores and put them in alphabetical order & remove accidental duplicates ]--
       ForEach ($Script:store in $Script:datastores)                                     #--[ Loop through datastores ]--
              if ($Script:store -notlike "*Local*"){
                     $Script:myObj = "" | Select-Object vCenter, Name, CapacityGB, UsedGB, PercFree              #--[ Create a custom object and define its properties ]--
                     #--[ Set the values of each property ]--
                     $Script:myObj.vCenter = $Script:VIServer
                     $Script:myObj.Name = $Script:store.name
                     $Script:myObj.CapacityGB = [math]::Round($Script:store.capacityMB/1024,$Script:digits)
                     $Script:myObj.UsedGB = [math]::Round(($Script:store.CapacityMB - $Script:store.FreeSpaceMB)/1024,$Script:digits)
                     $Script:myObj.PercFree = [math]::Round(100*$Script:store.FreeSpaceMB/$Script:store.CapacityMB,$Script:digits)
                     $Script:myColCurrent += $Script:myObj   
                     #--[ Add the object to the output array ]--    
              }
       }
       Disconnect-VIServer -Confirm:$False                                      #--[ Disconnect from Virtual Center ]--
}

$Script:myColCurrent | Export-Clixml -Path $Script:CurrentFile                  #--[ Export the output to an xml file; the new Current file ]--

$Script:CurrentDate = (Get-Item $Script:CurrentFile).LastWriteTime              #--[ Get file dates for new file names ]--
$Script:PreviousDate = (Get-Item $Script:PreviousFile).LastWriteTime

#--[Compare the Current information to that in the Previous file ]--------------
If (Test-Path $Script:PreviousFile){                                            #--[ Check if a Previous file exists ]--
       $Script:myColPrevious = Import-Clixml $Script:PreviousFile               #--[ Import the Previous file ]--
       $Script:myColCurrent= Import-Clixml $Script:CurrentFile                  #--[ Import the Previous file ]--

       $Script:myColDiff = @()                                                                                   #--[ Create an array to hold the differences ]--
       ForEach ($Script:myObjCurrent in $Script:myColCurrent){                  #--[ Loop through the current datastores ]--
           $Script:VCCurrent = $Script:myObjCurrent.vCenter
              $Script:RowData = ""
              $Script:diff = Compare-Object ($Script:myColPrevious | Where { $_.Name -eq $Script:myObjCurrent.Name }) $Script:myObjCurrent -Property PercFree  # The actual compare command
              $Script:myObjDiff = "" | Select-Object vCenter, VolName, PercentFree, Diff #--[ Create a custom object and properties for outputting results ]--
              $Script:myObjDiff.vCenter = $Script:myObjCurrent.vCenter                          #--[ Setting the values of each property ]--
              $Script:myObjDiff.VolName = $Script:myObjCurrent.Name                            
              $Script:myObjDiff.PercentFree = $Script:myObjCurrent.PercFree
                    
              #--[ The most important property is the calculated difference between the current and previous values of PercFree. You can substitute it for UsedGB if you like. ]--
              $Script:myObjDiff.Diff = ($Script:diff | Where { $_.SideIndicator -eq '=>' }).PercFree - ($Script:diff | Where { $_.SideIndicator -eq '<=' }).PercFree
                    
              If (($Script:myObjDiff.Diff -eq "") -or ($Script:myObjDiff.Diff -eq $null)){$Script:myObjDiff.Diff = "0.00"}
              $Script:myColDiff += $Script:myObjDiff                                                   #--[ Adding it to the output array ]--

              $Script:BGColor = "#dfdfdf"                                         #--[ Grey cell background ]--
              $Script:RowData += '<tr>'
                          
              if($Script:VCCurrent -eq "vcenter1"){                               #--[ NOTE: Tweak this name to keep colors rotating ]--
                     $Script:FGColor = "#408080"                                  #--[ Color to distinguish 1st vCenter ]--
              }ElseIf($Script:VCCurrent -eq "vcenter2"){                          #--[ NOTE: Tweak this name to keep colors rotating ]--
                     $Script:FGColor = "#808000"                                  #--[ Color to distinguish 2nd vCenter ]--
              }Else{
                     $Script:FGColor = "#000000"                                  #--[ Default color, black ]--
                     }
             
              $Script:RowData += '<td bgcolor=' + $Script:BGColor + '><font color=' + $Script:FGColor + '>' + $Script:myObjDiff.vCenter + '</td>'           

              $Script:FGColor = "#000000"
              $Script:RowData += '<td bgcolor=' + $Script:BGColor + '><font color=' + $Script:FGColor + '>' + $Script:myObjDiff.VolName + '</td>'           
              $Script:RowData += '<td bgcolor=' + $Script:BGColor + '><font color=' + $Script:FGColor + '>' + $Script:myObjDiff.PercentFree + '</td>'       
              If ($Script:myObjDiff.Diff -eq "0.00"){
                     $Script:FGColor = "#000000"                                   #--[ Black foreground for no change ]--
                     $Script:RowData += '<td bgcolor=' + $Script:BGColor + '><font color=' + $Script:FGColor + '>' + $Script:myObjDiff.Diff
              }ElseIf ($Script:myObjDiff.Diff -lt 0){
                     $Script:FGColor = "#700000"                                   #--[ Red foreground for storage loss]--
                     $Script:RowData += '<td bgcolor=' + $Script:BGColor + '><font color=' + $Script:FGColor + '><strong>' + $Script:myObjDiff.Diff + '</strong>'
              }Else
                     $Script:FGColor = "#007000"                                   #--[ Green foreground for storage gain ]--
                     $Script:RowData += '<td bgcolor=' + $Script:BGColor + '><font color=' + $Script:FGColor + '><strong>' + $Script:myObjDiff.Diff + '</strong>'
              }
                          
              $Script:RowData += '</td></tr>'
              $Script:ReportBody += $Script:RowData
              Clear-Variable diff -ErrorAction "SilentlyContinue"                                      #--[ Clearing the variable used inside the loop to prevent incorrect output in case of problems setting the variable! ]--
       }
       If ($Script:myColDiff.Length -eq 0){$Script:myColDiff = "No changes since last check."#--[ If nothing changed, we don't want an empty file. ]--
       $Script:myColDiff | Format-Table -AutoSize | Out-File $Script:DifferenceFile -Force -Append         #--[ And we conclude by outputting the results to a text file, which can be emailed or printed. ]--
}

If ($Script:myColDiff.Length -ne 0){
       (Get-Content $Script:DifferenceFile) | Where { $_ } | Set-Content $Script:DifferenceFile
       (Get-Content $Script:DifferenceFile) | Where {$_ -notmatch '----'} | Set-Content $Script:DifferenceFile
       Add-Content $Script:DifferenceFile –value "`nCurrent-Report $Script:CurrentDate &nbsp; &nbsp;`nPrevious-Report $Script:PreviousDate &nbsp; &nbsp;"
       $Script:FGColor = "#000000"
       $Script:BGColor = "#bbbbbb"
       $Script:RowData += '<tr>'
       $Script:RowData += '<td bgcolor=' + $Script:BGColor + '><font color=' + $Script:FGColor + '>Current Report</td>'    
       $Script:RowData += '<td bgcolor=' + $Script:BGColor + '><font color=' + $Script:FGColor + '>' + $Script:CurrentDate + '</td>'  
       $Script:RowData += '<td bgcolor=' + $Script:BGColor + '><font color=' + $Script:FGColor + '>Previous Report</td>'   
       $Script:RowData += '<td bgcolor=' + $Script:BGColor + '><font color=' + $Script:FGColor + '>' + $Script:PreviousDate + '</td>' 
       $Script:RowData += '</tr>'
       $Script:ReportBody += $Script:RowData
}

$Script:ReportBody += '</table><br><br>'
<#--[ Enable this section to add notes to the bottom of the report. ]--
$Script:ReportBody += '
<ul>
    <li>Only powered-on Vms are shown since the script relies on WMI to get the block size.</li>
       <li>"Vol", or "Volume" refers to a Windows disk partition.</li>
       <li>The hidden system partition, which is typically Vol 0 on Disk 0, is not shown.</li>
       <li>Disk numbers are assigned beginning with 0 (zero).</li>
       <li>Partition numbers are assigned beginning with 1 (not 0).</li>
</ul>'
#>
$Script:OutBody = Get-Content $Script:DifferenceFile #| Out-String
SendEmail $Script:OutBody

If ($Script:Console){Get-Content $Script:DifferenceFile | Out-String}

#--[ Cleanup ]--
$Script:attachment.Dispose()
$Script:msg.Attachments.Dispose()
$Script:msg.Dispose()
$Script:smtp.Dispose()
If ($Script:NoUpdate){
       If (Test-Path $Script:DifferenceFile){Remove-Item -Path $Script:DifferenceFile -force}
       If (Test-Path $Script:CurrentFile){Remove-Item -Path $Script:CurrentFile -force}
}Else{
       If (Test-Path $Script:DifferenceFile){rename-Item -Path $Script:DifferenceFile -newname ("$PSScriptRoot\SAN-Vol_{0:MM-dd-yyyy}_Diff.log" -f (Get-Date))}
       If (Test-Path $Script:PreviousFile){Remove-Item -Path $Script:PreviousFile -Force} #If a Previous file exists remove it
       If (Test-Path $Script:CurrentFile){Copy-Item -Path $Script:CurrentFile -Destination ("$PSScriptRoot\SAN-Vol_{0:MM-dd-yyyy}_Stats.xml" -f (Get-Date))}
       If (Test-Path $Script:CurrentFile){Rename-Item -Path $Script:CurrentFile -NewName $Script:PreviousFile}                    # If a Current file exists, rename this Current file to Previous
}
$Script:Credential = ""
$Script:CurrentFile = ""
$Script:PreviousFile = ""
$Script:DifferenceFile = ""
$Script:OutBody = ""

If ($Script:Console){Write-Host '--- Completed ---'}

#iex '$PSScriptRoot\reload.bat'  #--[ Used for input file refresh while debugging ]--