title: My script takes too long to run
body: <p>My script reports on event errors from the application, system and security logs within 24 hours. The script takes an average of 8 mins to run. I believe these particular statements contribute to the problem:</p>
  
  <pre><code>$Lap = Get-EventLog -computername $server -LogName $logname -after (Get-Date).AddHours(-24)
  $Lap | where {$_.entryType -match "Error"} | Sort-Object eventid |
    group-object eventid | Format-Table Name, Count -auto | fl |
    out-string | Add-Content $eventlogfile
  </code></pre>
  
  <p>If I replace the <code>-after</code> parameter with <code>-newest</code>, the script runs quickly. Any thoughts of why the above statement contributes to the script taking awhile to run?</p>
  
  <p><em>Edit</em>
  Doing some research, I learned that by using the get-eventlog cmdlet PS parses the entire event log.</p>
  
  <p><em>Measure how long it'll take to determine the amount of application errors found within the last 24 hours</em>
  <code>Measure-Command -Expression {get-eventlog -ComputerName server123 -LogName Application -EntryType Error -after (Get-Date).AddHours(-24)}</code>
  <br>
  <br>
  <strong>Total time: 54 secs</strong>
  <br>
  <br>
  Count how many application errors popped up in the last 24 hours* 
  
  <br>
  <code>$logs1 = get-eventlog -ComputerName server123 -LogName Application -EntryType Error -after (Get-Date).AddHours(-24)
   $logs1.count</code>
  <br>
  <br>
  <strong>There are 3 errors</strong>
  <br>
  <br>
  <code>measure-command -expression {get-eventlog -ComputerName server123 -logname application -Newest 3 }</code>
  <br>
  <br>
  <strong>43 milliseconds</strong></p>
  
  <p>Any thoughts of why specifying the <code>-after</code> parameter with the <code>get-eventlog</code> cmdlet returns results much longer than specifing the <code>-newest</code> parameter?</p>