PowerShell 7.3 - scenarios When Filtering Objects with Where-Object Inside a ForEach-Object
I'm maintaining legacy code that I've looked through the documentation and I'm still confused about I'm relatively new to this, so bear with me... I'm running into an scenario while trying to filter a collection of objects within a `ForEach-Object` loop using `Where-Object`. The primary goal is to process a large list of user accounts and only retain those that are enabled. However, when I apply my filter, it seems to be returning all objects instead of just the enabled ones. Here's a simplified version of my code: ```powershell $users = Get-ADUser -Filter * -Property Enabled | Select-Object Name, Enabled $enabledUsers = $users | ForEach-Object { $_ | Where-Object { $_.Enabled -eq $true } } $enabledUsers ``` I expected the `$enabledUsers` variable to contain only the accounts where `Enabled` is `$true`, but when I output it, I see all users regardless of their enabled status. Additionally, I noticed that the `Where-Object` filter is being applied to each user object individually within the loop. I have also tried restructuring the command using a pipeline directly: ```powershell $enabledUsers = Get-ADUser -Filter * -Property Enabled | Where-Object { $_.Enabled -eq $true } ``` This works as expected, but I want to stick to using `ForEach-Object` for further processing later in the pipeline. Is there a way to correctly filter enabled users while still utilizing `ForEach-Object`? Is there a fundamental misunderstanding in how Iām applying the filter? Any insights or best practices would be greatly appreciated! I'm working on a service that needs to handle this. I'd really appreciate any guidance on this. Am I missing something obvious? The project is a web app built with Powershell. What's the correct way to implement this? For reference, this is a production service. Thanks for taking the time to read this!