CodexBloom - Programming Q&A Platform

PowerShell 7.3 - Issues with Conditional Logic While Processing Files in a Loop

πŸ‘€ Views: 53 πŸ’¬ Answers: 1 πŸ“… Created: 2025-09-01
powershell conditional-logic file-processing PowerShell

I tried several approaches but none seem to work. After trying multiple solutions online, I still can't figure this out. I've looked through the documentation and I'm still confused about I'm trying to process multiple text files in a directory using PowerShell 7.3, and I need to implement some conditional logic based on the content of each file... The goal is to read each file, check for specific keywords, and then perform actions based on the presence of those keywords. However, I'm encountering unexpected behavior when I try to execute my conditionals. Here's the code I currently have: ```powershell $directoryPath = "C:\Logs" $keywords = @('Error', 'Warning', 'Info') Get-ChildItem -Path $directoryPath -Filter *.txt | ForEach-Object { $fileContent = Get-Content -Path $_.FullName foreach ($keyword in $keywords) { if ($fileContent -match $keyword) { Write-Host "Found '$keyword' in file: $($_.Name)" # Perform additional actions here based on the keyword } } } ``` When I run this script, it doesn't seem to match any keywords, even though I'm certain they exist in the files. I tried using `-like` instead of `-match`, but it didn't resolve the issue. Additionally, if I use `Select-String`, the output appears correctly, indicating that the keywords are indeed present in the files. Here’s the error I see when I add a debug message to check the `$fileContent`: "Cannot index into a null array." This suggests that `$fileContent` might not be populated correctly. I suspect it might be an issue with how `Get-Content` is reading the files in the loop. Any suggestions on how to resolve this or improvements to make the script work as intended? Also, would there be a performance impact if I had a large number of files (let's say over a thousand) in the directory? For context: I'm using Powershell on Ubuntu. Any ideas what could be causing this? I'm open to any suggestions. My team is using Powershell for this mobile app.