yesIamFaded
yesIamFaded

Reputation: 2068

PowerShell Nested Loop inner Loop doesnt work?

Hi first Question on PowerShell,

I need to write a script that takes a log file and do some calculation in it.

I am reading the log file correctly and then I am creating two arrays that only contain the lines that I need from the file.

$inVar = Select-String -path C:\Dev\Script\Ldorado.log  -pattern "IN:"             
$outVar = Select-String -path C:\Dev\Script\Ldorado.log -pattern "OUT:"

I get back every line where there is an IN in 1 array and OUT in the other.

I managed to split the lines to only get the dates in each line - by using .Lines.Split("(")

If I have the two date values from the array I can calc the timespan with New-TimeSpan and some converting.

Now I need to somehow do this for every entry there is inside the file that matches the pattern, so I think I need a Loop or even a nested Loop. I tried every Loop (for / foreach / foreachObject / while...) but with no luck.

For example if you look at this code:

foreach ($out in $outVar) {
$testVar = $out.Line.Split("(")[0]
    foreach ($in in $inVar) {
        $testIn = $in.Line.Split("(")[0]
    }
    Write-Host $testVar + $testIn
}

my Output looks like this:

12:55:49  + 13:20:31 
12:55:49  + 13:20:31 
12:55:49  + 13:20:31 
13:54:35  + 13:20:31 
13:54:35  + 13:20:31 
13:54:35  + 13:20:31 
16:37:44  + 13:20:31 
16:37:44  + 13:20:31 
16:37:44  + 13:20:31 
17:15:23  + 13:20:31 
17:15:23  + 13:20:31 
17:15:23  + 13:20:31 
 9:06:13  + 13:20:31 
 9:06:13  + 13:20:31 
 ...

Having every value 3 times is correct because there are always IN's and 3OUT's for every log.

The outer loop seems to work correctly but the nested Loop just takes the last value there is and prints it - instead I want to have the same behavior as the outer loop where it actually loops.

Anyone knows how I can solve this?

Upvotes: 1

Views: 600

Answers (2)

user11829835
user11829835

Reputation:

You can add the results into arrays then output them in the desired format. Like the following

#Empty arrays
$testIn_arr = @()
$testVar_arr = @()
foreach ($out in $outVar) {
$testVar = $out.Line.Split("(")[0]
$testVar_arr += @($testVar)
}

foreach ($in in $inVar) {
$testIn = $in.Line.Split("(")[0]
$testIn_arr += @($testIn)
}

for ($i = 0; $i -lt $testIn_arr.Count; $i++)
{
 Write-Host $($testVar_arr[$i]) + "+" + $($testIn_arr[$i])
}

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

Use a for loop so you can grab the values at the same index from each array (this assumes $outVar and $inVar are aligned and of the same length):

for($i = 0; $i -lt $outVar.Length; $i++) {
    $testVar = $outVar[$i].Line.Split("(")[0]
    $testIn  = $inVar[$i].Line.Split("(")[0]
    Write-Host $testVar + $testIn
}

Upvotes: 0

Related Questions