A seperate issue with Foreach loops and Eventlogs

by Feb 12, 2011

This script should have three nested loops. 

  1. the first is a loop through all computers from a list
  2. the second is a loop through all eventlogs on a computer
  3. the third loop writes each event from each eventlog to SQL table.

I assume using functions is a better practice.  That may be/probably is related to error I am receiving. The Script works fine if I don't use the first two loops.

So, perhaps someone could 1) explain to me why my foreach loops are broken; and 2) give me some hints to break these down into reusable functions.

 

**********************

Error:

Get-EventLog : The event log 'System.Diagnostics.EventLog' on computer 'xxxxxxxxxxx' does not exist.
At C:Scripts2010 Feb 11.ps1:7 char:31
+                 $LogExtract = Get-EventLog <<<<  -computername $Machine -LogName $Logtype -Newest 10 | Select-
Object -Property MachineName,EventID,EntryType,Message,Source,InstanceId,TimeGenerated,UserName
    + CategoryInfo          : NotSpecified: (:) [Get-EventLog], InvalidOperationException
    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetEventLogCommand

*********************

$ListofComputers = (Get-Content c:listofcomputers.txt)
 
  foreach ($Machine in $ListofComputers){
  $ExistingLogs = Get-EventLog -List -ComputerName $Machine
   foreach ($Logtype in $ExistingLogs){
    $LogExtract = Get-EventLog -computername $Machine -LogName $Logtype -Newest 10 | Select-Object -Property MachineName,EventID,EntryType,Message,Source,InstanceId,TimeGenerated,UserName
        
    $conn = New-Object System.Data.SqlClient.SqlConnection ("Data Source=SQLSERVER;Initial Catalog=Documentation;Integrated Security=SSPI")
    $conn.Open()
    $cmd = $conn.CreateCommand()
     foreach ($Event in $LogExtract) {
       $cmd.CommandText ="INSERT into Stuff VALUES (`
       '$($Event.MachineName)',
       '$($LogType.LogDisplayName)',
       '$($Event.EventID)',
       '$($Event.EntryType)',
       '$($Event.Message)',
       '$($Event.Source)',
       '$($Event.InstanceID)',
       '$($Event.TimeGenerated)',
       '$($Event.UserName)'
       )"
       $cmd.ExecuteNonQuery()
      } 
     $conn.Close()
   }
  }