I'm building a script to monitor my event logs. This command gathers only "Error" and "Warning" messages and places them into the $entries array.

$entries = $log.Entries |
? {$_.TimeWritten -gt ($(Get-Date).AddDays(-2)) -and `
(($_.EntryType -like "Error") -or `
($_.EntryType -like "Warning"))} |
Format-Table -wrap

If I output $entries in the console, it displays what I want - the log entries - but if I pipe this out to a text file (Add-Content $output $entries) I get the .NET class name only (System.Diagnostics.EventLogEntry). I have also tried foreach ($entry in $entries) with similar results.

What's the basic PowerShell principle I'm missing here?

link|improve this question

68% accept rate
1  
Not really an answer, but might help you: bear in mind powershell pipes objects (.net objects), NOT text like the bash and co of old. You are actually piping the objects (hense why you are getting the output you are) and need to convert this into the text you require. – Splash Aug 25 '09 at 14:40
feedback

2 Answers

up vote 1 down vote accepted

Basically - the add-content/set-content command just do a ToString() on whatever you pass to it. For many .NET objects, that is just the class name.

If you do:
out-string -inputobject $entries | add-content "yourfile.txt"

That should properly convert to a string and output it to your text file.

link|improve this answer
This worked great! Thanks for the very useful tip. – Doug Chase Aug 25 '09 at 15:15
feedback

Add-content will give you this behavior, if you want the fields rather than the object description then the simplest approach is to just use traditional file redirection e.g.

$entries > $output

or

$entries >> $output

if you want to append. This works as I would expect it to for your example code while your example of

Add-Content $output $entries

Only outputs the object type description (e.g. Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData ) for me.

link|improve this answer
You know, I tried this and it didn't behave the way I expected it to. These commands did not add anything to my text file for some reason. – Doug Chase Aug 25 '09 at 15:16
Interesting - I just checked on another system and it does work as expected for me, very strange. Get-Host tells me I'm running V1.0.0.0, on Vista in both cases. At least Mattb's suggestion worked. :) – Helvick Aug 25 '09 at 17:07
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.