title: Write a small script to extract ms-exchange audit logs in csv format?
body: <p><strong>Background</strong></p>
  
  <p>I'm using ms-exchange 2013 in my environment, and have a separate siem box which analyze logs produced by different systems (i.e exchange). The logs for exchange are internally stored and can however be extracted such as </p>
  
  <blockquote>
    <p>Get-MailboxAuditLog -Identity test-mailbox-1 -LogonTypes
    Admin,Delegate –ShowDetails -StartDate mm/dd/2014 -EndDate mm/dd/2014
    | Export-Csv “c:\test-Audit-Results.csv”</p>
  </blockquote>
  
  <p><strong>Steps taken so far</strong></p>
  
  <ul>
  <li>Enabling audit on exchange</li>
  <li>Got the command google which needs to put in a script (above).</li>
  </ul>
  
  <p><strong>My requirements (in algo)</strong> </p>
  
  <pre><code>1) check presence of properties file with last collect time. 
  2) If file is absent query the data from some period of time before till the current moment:
      2.1) Search-AdminAuditLog -StartDate (get-date).adddays(-30) -EndDate (get-date) | Export-Csv "c:\admin-results-temp.csv"
      2.2) remember "get-date" value to properties file
      2.3) copy "admin-results-temp.csv" file contents to the final file &lt;admin-final.csv&gt; to be forwarder by ALE
  3) **If file is present:**
      3.1) Get last collect time calculate difference in time from present time. If time-difference is more then 1 hours ...pull the log again
      3.2) execute Search-AdminAuditLog with StartDate = date from props file, EndDate = current 
      3.3) remember current time to the props file
      3.4) copy "admin-results-temp.csv" file contents to the final file &lt;admin-final.csv&gt; to be forwarder by ALE
  4) You can clean up final file &lt;admin-final.csv&gt; once a week to avoid over-grow. ALE will forward it from the beginning at that case.
  5) Schedule the script/code described above to run each minute
  6) Configure ALE in a File Forwarder mode to send &lt;admin-final.csv&gt; file
  </code></pre>
  
  <p>note:on part of ALE that part is already automated. No need for file-forwarding required.</p>
  
  <p>I want to above algo in power shell script.</p>
  
  <p><strong>CURRENT-CODE</strong></p>
  
  <pre><code>&lt;#
  .SYNOPSIS
  Get-MailboxReport.ps1 - Mailbox report generation script.
  
  .DESCRIPTION 
  Generates a report of useful information for
  the specified server, database, mailbox or list of mailboxes.
  Use only one parameter at a time depending on the scope of
  your mailbox report.
  
  .OUTPUTS
  Single mailbox reports are output to the console, while all other
  reports are output to a CSV file.
  
  .PARAMETER all
  Generates a report for all mailboxes in the organization.
  
  .PARAMETER server
  Generates a report for all mailboxes on the specified server.
  
  .PARAMETER database
  Generates a report for all mailboxes on the specified database.
  
  .PARAMETER file
  Generates a report for mailbox names listed in the specified text file.
  
  .PARAMETER mailbox
  Generates a report only for the specified mailbox.
  
  .PARAMETER filename
  (Optional) Specifies the CSV file name to be used for the report.
  If no file name specificed then a unique file name is generated by the script.
  
  .EXAMPLE
  .\Get-MailboxReport.ps1 -database HO-MB-01
  Returns a report with the mailbox statistics for all mailbox users in
  database HO-MB-01
  
  .EXAMPLE
  .\Get-MailboxReport.ps1 -file .\users.txt
  Returns a report with the mailbox statistics for all mailbox users in
  the file users.txt. Text file should contain names in a format that
  will work for Get-Mailbox, such as the display name, alias, or primary
  SMTP address.
  
  .EXAMPLE
  .\Get-MailboxReport.ps1 -server ex2010-mb1
  Generates a report with the mailbox statisitcs for all mailbox users
  on ex2010-mb1
  
  .EXAMPLE
  .\Get-MailboxReport.ps1 -server ex2010-mb1 -filename ex2010-mb1.csv
  Generates a report with the mailbox statisitcs for all mailbox users
  on ex2010-mb1, and uses the custom file name of ex2010-mb1.csv
  
  .LINK
  
  .NOTES
  Written By: SOC
  
  Change Log
  V1.00, 2/2/2012 - Initial version
  #&gt;
  
  #...................................
  # Variables
  #...................................
  
  $check_collect_last
  
  #...................................
  # Initialize
  #...................................
  
  #Set recipient scope
  $2007snapin = Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Admin
  if ($2007snapin)
  {
      $AdminSessionADSettings.ViewEntireForest = 1
  }
  else
  {
      $2010snapin = Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010
      if ($2010snapin)
      {
          Set-ADServerSettings -ViewEntireForest $true
      }
  }
  
  
  #If no filename specified, generate report file name with random strings for uniqueness
  
      $source=c:\results-audit        
      $check_last = (ls $source).LastWriteTime
  
  
  
  #...................................
  # Script
  #...................................
  
  #Add dependencies
  Import-Module ActiveDirectory
  
  #Get the mailbox list
  
  $mailboxcount = $mailboxes.count
  $i = 0
  
  $mailboxdatabases = @(Get-MailboxDatabase)
  
  $directoryInfo = Get-ChildItem C:\Mail-audit-results | Measure-Object
  $directoryInfo.count #Returns the count of all of the files in the directory
  
  If $directoryInfo.count -eq 0
  
  {
  
  #Loop through mailbox list
  foreach ($mb in $mailboxes)
  {
      $i = $i + 1
      $pct = $i/$mailboxcount * 100    
  
      Write-Progress -Activity "Collecting audit details for Mail admin" -Status "Processing mailbox $i of $mailboxcount - $mb" -PercentComplete $pct
  
       $Startdate=((Get-Date).adddays(-30)).ToShortDateString()
       $Enddate=(Get-Date).ToShortDateString()
       $check_collect_last=Get-Date -format HH:mm:ss
  
  
      $auditAdmin_search = $mb | Search-MailboxAuditLog -Identity $i -LogonTypes Admin,Delegate –ShowDetails -StartDate  $Startdate -EndDate $Enddate | Export-Csv “c:\Mail-audit-results\Temp-Audit-Results.csv”   
  
  
     #appending file to final audit csv file
     [System.IO.File]::ReadAllText("c:\Mail-audit-results\Temp-Audit-Results.csv") | Out-File c:\Mail-audit-results\Final-mail-admin.csv -Append -Encoding Unicode 
  
  }
  
  }
  
  else
      # if difference between last collect time and present is more then #1 hours collect logs in cycle / hrs
  $Now = Get-Date -format HH:mm:ss
      $check_collect_last = New-TimeSpan $check_collect_last $Now
  
      if ($check_collect_last.Hours -gt 1) 
      {
  
      foreach ($mb in $mailboxes)
  {
  
  $i = $i + 1
      $pct = $i/$mailboxcount * 100    
  
      Write-Progress -Activity "Collecting audit details for Mail admin" -Status "Processing mailbox $i of $mailboxcount - $mb" -PercentComplete $pct
       $Startdate=((Get-Date).ToShortDateString()
       $Enddate=(Get-Date).ToShortDateString()
  
      $auditAdmin_search = $mb | Search-MailboxAuditLog -Identity $i -LogonTypes Admin,Delegate –ShowDetails -StartDate   -EndDate $Enddate | Export-Csv “c:\Mail-audit-results\Temp-Audit-Results.csv
      $check_collect_last=$Startdate
  
  }
  
      }
  
      else
      return 0
  </code></pre>
  
  <p>This is my first powershell script; I appreciate If someone can suggest/review If possible. Thanks esp in regard to date functions.</p>