windowspowershellvariablesout-gridview

Powershell - Variables and foreach loop


This thread got me started very well, but now I need more help

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.

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.

My confusion comes regardinf variable declaration, type, appending and placement in the code...

I'm just learning PS now, so this may be a little basic for you :)

this code works...need to add in the variable idea in the right places:

#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.

Thanks!

Kevin3NF


Solution

  • Just to close this out, I used suggestions from mutiple comments:

    $sys = @() (outside the loop)

    $sys += Get-EventLog (inside the loop)

    $sys | Export-Csv (after the loop to send to .csv)

    I even blogged the whole thing, including all the various iterations of learning I went through: http://dallasdbas.com/getting-to-know-powershell-from-an-old-dba/

    Thanks to all that helped. This gave me a framework I will continue to use on these servers as the needs arise.

    Kevin3NF