PowerShell 7.3 - implementing Conditional Logic in Nested Loops for File Processing
I'm confused about I'm working on a project and hit a roadblock... After trying multiple solutions online, I still can't figure this out. I'm working with PowerShell 7.3 to process a set of text files in a directory. My goal is to read each file, extract specific lines based on certain conditions, and then output the results to a new file. However, I'm running into issues when using nested loops for conditional logic, which leads to unexpected behavior. Here's a simplified version of my code: ```powershell $inputPath = "C:\Logs" $outputPath = "C:\ProcessedLogs\results.txt" $results = @() Get-ChildItem $inputPath -Filter '*.txt' | ForEach-Object { $fileContent = Get-Content $_.FullName foreach ($line in $fileContent) { if ($line -match 'behavior') { $errorDetails = $line foreach ($errorLine in $fileContent) { if ($errorLine -match 'Timestamp') { $results += "behavior found in $($_.Name): $errorDetails at $errorLine" } } } } } $results | Out-File -FilePath $outputPath ``` Despite following this structure, I often receive an incomplete output where the `Timestamp` lines do not always match the corresponding `behavior` lines. Occasionally, the script seems to hang or take an unusually long time to complete, especially with larger files. I've tried adding some `Write-Host` statements to debug which part of the loop is executing, but it hasn't helped clarify the scenario. I'm also unsure if thereβs a more efficient way to handle these nested loops or if I should be using a different approach altogether. When my files have a large number of lines, the execution time increases significantly. I would appreciate any insights on optimizing the loops or suggestions for handling this file processing task more effectively. What's the best practice here? Am I missing something obvious? I'm open to any suggestions.