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?
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.
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.
or
if you want to append. This works as I would expect it to for your example code while your example of
Only outputs the object type description (e.g. Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData ) for me.
Piping via: | Add-Content $output
does not appear to work well, when the content being piped contains numerous lines.
For example:
In the above example, the test.txt file gets properly created, including the opening comment. However, the Get-ItemProperty output appears as Chinese characters.