Return other properties when using Select-String

by SQLRunr at 2012-09-17 13:09:24

I have a log object which has multiple properties, one of which has the log messages in a property called Text. Another property is the date/time of the message. I’m using the following command:

$log | select-string -inputobject {$.Text} -pattern ‘Error:’ -context 0,1

Unfortunately it only returns what’s in the Text property. Is there a way to also return the other corresponding properties?


by RichardSiddaway at 2012-09-17 13:30:58
could you try something like this

$data = $log | select-string -inputobject {$
.Text} -pattern ‘Error:’ -context 0,1

if ($data){ do your stuff here }
by SQLRunr at 2012-09-17 14:38:07
Unfortunately there’s no ‘key’ information in the Text property that could link back to the other properties. I was hoping that select-string with the -inputobject property would preserve that object integrity somehow.
by Klaas at 2012-09-18 00:44:44
Do you mean your $log is a collection of log objects and you want to filter out the objects that contain ‘Error:’?

Would this help you?:
$log | Where {$.Text -match ‘Error:’} | Select Date,Text
by SQLRunr at 2012-09-18 12:18:14
Thanks, Klaas but that returns a whole lot of blank rows if I add the context parameter. Looks like I’ll need to load the text file with the log rather than the log object. :frowning:
by Klaas at 2012-09-19 01:36:44
Why exactly do you need the -context ? If it’s just to truncate the text, maybe you could use the substring method:

$log | Where-object {$
.Text -match ‘Error:’} | Select-object Date,@{name=‘message’,expression={$_.Text.substring(0,160)}}

If you would choose to work with text instead of objects, I think you’re going to have a lot more work with all the conversion and matching.