I'm trying to automate a process, essentially we receive an error code and line numbers for a file. The script I'm writing needs to get the error code and line numbers, then dive into the file and retrieve the lines.
Everything is working except parsing the error code and line numbers into some sort of useable format so I can loop through them
The format is:
Error code Line number
1234 00232,00233,00787
3333 00444
1111 01232,2132
I've tried
$a = $a -replace "\s+","="
$a|ConvertFrom-StringData
But I'm drawing a blank when it comes to looping through the hashtable and dealing with the occasional CSV values.
I did think of converting the whole thing to a CSV but I'm running up against the edge of my knowledge...
Use a regular expression that matches a space followed by either a digit or an upper case letter, then replace said match with a delimiter and finally parse the resulting string as a CSV document:
# read target file into memory for later extraction
$fileContents = Get-Content C:\path\to\source\file.txt
# define error report, replace with `Get-Content` if data if coming from file too
$errorReport = @'
Error code Line number
1234 00232,00233,00787
3333 00444
1111 01232,2132
'@
# replace the middle space and parse as CSV
$errorMappingList = $errorReport -replace '(?-i) (?=\p{Lu}|\d)', '|' |ConvertFrom-Csv -Delimiter '|'
# go through each entry in the error mapping list
foreach($errorMapping in $errorMappingList){
# go through each line number associated with the error code
foreach($lineNo in $errorMapping.'Line Number' -split ','){
# extract the line from the file contents, output 1 new object per line extracted
[pscustomobject]@{
ErrorCode = $errorMapping.'Error code'
LineNumber = $lineNo
Line = $fileContents[$lineNo - 1]
}
}
}