1

I have several logs files with hundreds of lines in the following format:

{"time": 0800, "service":"A service", "id": 5, "error":"bad"}  
{"time": 0900, "service":"B service", "id": 6, "error":"good"}  

I'd like to be able run through each file and output a table with a count of each unique error message .. something like this:

Error "bad" came up 5 times

Error "good" came up 3 times

I'm not sure if converting the content to JSON makes sense in this situation, but I have done the following so far to at least identify unique strings:

Get-Childitem -path "\path" | Select-string -Pattern "good"

and that gives me all the "good" messages.

It would seem to me that using a loop with a counter to capture unique events could be used. What would be the best way to achieve all of this with PowerShell?

1
  • Just a headsup, you can pipe your Command to Measure-Object and it will return you the number of lines. Commented Aug 2, 2018 at 9:42

1 Answer 1

4

Convert the json strings in the file into objects with ConvertFrom-Json and then group them by the error property using Group-Object:

Get-Childitem -path "\path" |ConvertFrom-Json |Group-Object error -NoElement
Sign up to request clarification or add additional context in comments.

2 Comments

@Avshalom Argh, sorry dude, story of my life :-P
great, that worked. One of the files is formatted in a way where the convertfrom-json cmdlet doesn't like it. There is only one line and it is like this, { "error" : "bad"}, but it is spread out on 3 lines. The error thrown is "Invalid object passed in ':' or '}". How can I skip files where the json is not recognized.. or how can I change it so it is recognized? Second follow up question. How can I access the properties of the object? For example, I want to display the "service" and "time" properties. I only get count, group, and name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.