CodexBloom - Programming Q&A Platform

PowerShell 7.3 - Difficulty with Conditional Logic in a Foreach-Object Loop for JSON Parsing

👀 Views: 84 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-08
powershell json foreach-object Powershell

I'm relatively new to this, so bear with me..... I'm currently working on a script in PowerShell 7.3 where I need to parse a JSON file containing user data, but I'm running into issues with applying conditional logic inside a `ForEach-Object` loop. The JSON structure looks like this: ```json [ { "name": "Alice", "age": 30, "status": "active" }, { "name": "Bob", "age": 25, "status": "inactive" }, { "name": "Charlie", "age": 35, "status": "active" } ] ``` I want to filter the active users and then create a custom object for each active user that includes the name and age. Here's the code I've written so far: ```powershell $jsonData = Get-Content -Path 'users.json' | ConvertFrom-Json $activeUsers = $jsonData | ForEach-Object { if ($_.status -eq 'active') { [PSCustomObject]@{ Name = $_.name Age = $_.age } } } ``` However, when I run this script, I end up with an array that contains some `null` values, which I didn't expect. After debugging, I found out that the `ForEach-Object` is returning `null` for the inactive users, but I only want the active ones. I tried wrapping the entire block in a `Where-Object` as well: ```powershell $activeUsers = $jsonData | Where-Object { $_.status -eq 'active' } | ForEach-Object { [PSCustomObject]@{ Name = $_.name Age = $_.age } } ``` This approach works, but I feel like I'm overcomplicating it. Is there a more efficient way to achieve this without getting null values? Any insights on best practices for handling such scenarios would be greatly appreciated! For context: I'm using Powershell on Windows. Am I missing something obvious? Thanks for taking the time to read this! I'm working on a web app that needs to handle this. Could this be a known issue?