I have a file containing logs for months and I want to store only the logs for a specific data into a csv file.
sample log data:
2022-06-21 09:06:09 15SS1B Equip = Z39 Text -0003254 Equipment has been added on-line
2022-07-21 09:06:09 15SS2B Equip = Z40 Text -0003254 Equipment has been added on-line
2022-08-21 09:06:09 15SS3B Equip = Z41 Text -0003254 Equipment has been added on-line
2022-09-21 09:06:09 15SS4B Equip = Z42 Text -0003254 Equipment has been added on-line
I get the result with the following columns: IgnoreCase, LineNumber, Line, Filename, Path, Pattern, Context, Matches. I'm only interested in the result of Line column only.
Appreciate your help. Thanks.
This is my code:
$data = Get-Content '\log.log' | Select-String -Pattern "2022-08-21" | Export-CSV -Path '\output.csv' -NoTypeInformation
my request is to get that content and export them into new table like:
Date Time Number Type
2022-06-21 09:06:09 15SS1B Equip
CodePudding user response:
Are you looking for something like this, I did it for one line, the same can be used for multiple lines also.
$line = "2022-06-21 09:06:09 15SS1B Equip = Z39 Text -0003254 Equipment has been added on-line"
$data = $line.Split("=")[0]
$result = $data.Split(" ") # A Space in between quotes
[pscustomObject]@{
Date = $result[0]
Time = $result[1]
Number = $result[2]
Type = $result[3]
}
CodePudding user response:
I would use a regular expression on this in order to parse out the wanted parts and output these as properties of objects:
$dateToSearch = '2022-08-21'
$regex = "^(?<date>$dateToSearch)\s (?<time>\d{2}:\d{2}:\d{2})\s (?<number>[a-z\d] )\s (?<type>\w )\s =\.*"
Get-Content -Path '\log.log' | Where-Object { $_ -match $regex } |
Select-Object @{Name = 'Date'; Expression = {$matches['date']}},
@{Name = 'Time'; Expression = {$matches['time']}},
@{Name = 'Number'; Expression = {$matches['number']}},
@{Name = 'Type'; Expression = {$matches['type']}} |
Export-CSV -Path '\output.csv' -NoTypeInformation
Or use a loop instead of calculated properties:
$dateToSearch = '2022-08-21'
$regex = "^(?<date>$dateToSearch)\s (?<time>\d{2}:\d{2}:\d{2})\s (?<number>[a-z\d] )\s (?<type>\w )\s =\.*"
Get-Content -Path '\log.log' | Where-Object { $_ -match $regex } | ForEach-Object {
[PsCustomObject]@{
Date = $matches['date']
Time = $matches['time']
Number = $matches['number']
Type = $matches['type']
}
} | Export-CSV -Path '\output.csv' -NoTypeInformation
Result
Date Time Number Type
---- ---- ------ ----
2022-08-21 09:06:09 15SS3B Equip