CodexBloom - Programming Q&A Platform

PowerShell 7.3 - guide with Conditional Execution in Foreach-Object Loop Not Triggering Correctly

šŸ‘€ Views: 3 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-11
PowerShell ActiveDirectory foreach-object

I'm refactoring my project and Quick question that's been bugging me - I'm experimenting with I'm working on a project and hit a roadblock... After trying multiple solutions online, I still can't figure this out. I've been trying to process a list of users and check if their accounts are expired using PowerShell 7.3. I've set up a `foreach` loop with `ForEach-Object` to evaluate each user's status, but it seems that the conditional checks within the loop are not triggering as expected. Here's the relevant snippet of my code: ```powershell $userList = Get-Content 'C:\Users\userlist.txt' $userList | ForEach-Object { $user = $_ $userInfo = Get-ADUser -Identity $user -Properties AccountExpirationDate if ($userInfo.AccountExpirationDate -lt (Get-Date)) { Write-Host "Account for $user has expired." } else { Write-Host "Account for $user is active." } } ``` I've confirmed that the `userlist.txt` contains valid usernames and that the `Get-ADUser` cmdlet works fine when executed individually. However, I’m getting output that suggests all accounts are active, even when I know some should have expired. I also noticed that there are no errors, but the logic seems to overlook the expired accounts. To troubleshoot, I added write-debug statements to verify what `AccountExpirationDate` is returning: ```powershell if ($userInfo.AccountExpirationDate -lt (Get-Date)) { Write-Debug "Debug: $userInfo.AccountExpirationDate is less than current date." } ``` But even with this debug output, it appears that the condition is never true for the expired accounts. Could this possibly be a data type scenario with the date comparisons? I checked the format of `AccountExpirationDate` to ensure it's a DateTime object, but I'm still stumped. Any insights on what might be going wrong or how I can fix the conditional checks in the loop? Is there a better approach? Am I missing something obvious? I'm on Windows 11 using the latest version of Powershell. The project is a desktop app built with Powershell. Is there a simpler solution I'm overlooking? I'm coming from a different tech stack and learning Powershell. Any feedback is welcome!