Iterate a string in Powershell to create multiple variables

Leoš Marek 21 Reputation points
2022-11-18T12:12:29.627+00:00

Hi,
looking for a help to parse a string in powershell, that I acquire from a log file. Heres the string example.

Start of task1
Number of errors:0
End of task
Start of task 2
ERR something went wrong
ERR another thing went wrong
Number of errors: 2
End of task

Now I would need to create a separate variable that I can further work with, which only contains information for a given task. There can be multiple tasks in the log file and each task can have random number of lines, depending on number of errors.
Is this possible somehow? So far cant find a way to do it.
Cheers Leos

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 36,291 Reputation points
    2022-11-18T14:19:06.223+00:00

    Here's one way to process a log file.

    $AllTasks = @()   
    $entries = @()  
    $log = Get-Content c:\temp\x.txt   
    $capture = $false   
    foreach ($row in $log) {  
        if ($row.StartsWith("End of task")) {        # look for whatever indicates an end   
            $capture = $false  
            $AllTasks += [PSCustomObject]@{  
                    ID       = $taskid  
                    Messages = $entries   
            }   
            $entries = @()  
        }  
        if ($capture) {  
            $entries += $row  
        }  
        if ($row.StartsWith("Start of task")) {      # look for whatever indicates a start    
            $capture = $true  
            $taskid = $row.Substring(13).trim()      # whatever comes after start of task     
        }  
      
    }  
    "Processing done."  
    "We found {0} tasks." -f $AllTasks.count  
     foreach ($task in $AllTasks) {  
        "Task id is {0}" -f $task.id  
        foreach ($msg in $task.Messages) {  
            "    {0}" -f $msg  
        }  
    }                 
    

    Based on what you posted, it should produce this output.

    Processing done.
    We found 2 tasks.
    Task id is 1
    Number of errors:0
    Task id is 2
    ERR something went wrong
    ERR another thing went wrong
    Number of errors: 2

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Leoš Marek 21 Reputation points
    2022-11-18T16:57:46.57+00:00

    Thanks a lot man, I will adapt that to my exact needs.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.