Exit-Event.ps1

function Exit-Event
{
  <#
      .SYNOPSIS
      Logs various information about the script before leaving with return code to which 1000 has been added (for compatibility with SolarWinds checks)
      If a temporary admin user was created then delete it
      Adds to $global:debug, 'runtime' & ErrorCount & $ExitCode
      If $global:debug is set then write $global:Output to console
      Writes an EventID $ReturnCode with text $global:Output into the log defined in $global:EventLog with event source set as defined in $global:EventSource and EntryType as INFORMATION
          
      .EXAMPLE
      Exit-Event 1
  #>

  param ([Parameter(Mandatory=$true)][Int]$ReturnCode)
    
  Write-Event "########################"
  $evtinfo = "Stop " + $MyInvocation.ScriptName
  Write-Event $evtinfo

  $EndTime = get-date

  [int]$TotalDurationSeconds = ($EndTime - $Global:StartTime).TotalSeconds 
  [int]$Durationminutes = ($EndTime - $Global:StartTime).TotalMinutes
  $DurationSeconds = ($EndTime - $Global:StartTime).Seconds

  if ($DurationSeconds -gt 60) {
    Write-Event "RunTime : $Durationminutes m $DurationSeconds s"
  }
  else
  {
    Write-Event "RunTime : $TotalDurationSeconds s"
  }
  
  Write-Event "ErrorCount : $Global:ErrorCount"
       
  if ($ReturnCode -eq 0)
  {   
    Write-Event "ReturnCode : $ReturnCode"
    $evtinfo =$global:EventOK + " <br>" +  $Global:nl + "<br>" + $Global:nl + $global:Output
    Write-EventLog -LogName $global:EventLog  -Source $global:EventSource -EntryType Information -EventID $ReturnCode -Message $evtinfo 
  }
  else
  {
    if ($ReturnCode -le 1000) { $ReturnCode += 1000}
    Write-Event "ReturnCode : $ReturnCode"
    $evtinfo = $global:EventERROR + " <br>" +  $Global:nl + "<br>" + $Global:nl  +  $global:Output
    Write-EventLog -LogName $global:EventLog  -Source $global:EventSource -EntryType Error -EventID $ReturnCode -Message $evtinfo
  }

  exit $ReturnCode
}