title: Powershell - Variables and foreach loop
body: <p><a href="https://stackoverflow.com/questions/40939147/powershell-get-eventlog-for-multiple-servers">This thread</a> got me started very well, but now I need more help</p>
  
  <p>I am trying to loop through my serverlist.txt file, and pass the results of Get-EventLog to Out-GridView and then on to a .csv file.  I have this working, but I have to select all the records in the GridView window then click OK for each server.</p>
  
  <p>So, I have the idea that I want to create a $sys variable outside the loop, go in, append the results to that variable for each server, and then exit the loop and pass $sys over to Grid-view.</p>
  
  <p>My confusion comes regardinf variable declaration, type, appending and placement in the code...</p>
  
  <p>I'm just learning PS now, so this may be a little basic for you :)</p>
  
  <p>this code works...need to add in the variable idea in the right places:</p>
  
  <pre><code>#Drop the existing files
  Remove-Item C:\system.csv
  
  # SERVER LIST PROPERTIES
  # Get computer list to check disk space. This is just a plain text file with the servers listed out.
  $computers = Get-Content "C:\ServerList.txt"; 
  
  #Declare $sys here ??
  
  # QUERY COMPUTER SYSTEM EVENT LOG
  foreach($computer in $computers)
  
  {        
   if(Test-Connection $computer -Quiet -Count 1)
          {
     Try {
          # $sys = 
          Get-EventLog -ComputerName $computer -LogName System -EntryType "Error","Warning" -After (Get-Date).Adddays(-7) `
          | Select-Object -Property machineName, EntryType, EventID, Source, TimeGenerated, Message `
          | Out-GridView -PassThru | Export-Csv C:\System.csv -NoTypeInformation -Append;
         } 
     Catch 
         {
         Write-Verbose "Error $($error[0]) encountered when attempting to get events from  $computer"
         }
         } 
     else {
           Write-Verbose "Failed to connect to $computer"
          }
  
  
  }
  # $sys | Out-GridView....etc.
  </code></pre>
  
  <p>Thanks!</p>
  
  <p>Kevin3NF</p>