I'm having trouble with a PowerShell function I created to retrieve a list of users using the Get-ADUser cmdlet. The function was specifically designed to generate a report for leadership, as they request a list of accounts that haven't logged in for the last 90 days. My latest addition to the function is a line that checks if LastLogonDate is less than or equal to 90 days ago: `($_.LastLogonDate -le (Get-Date).AddDays(-90))`. However, it seems like this line is being ignored when I call the function; it returns all accounts, including those that logged in today. Interestingly, if I copy the entire command except for the function name and run it manually, it works as expected. I'd appreciate any insights into why this might be happening!
3 Answers
It sounds like there might be an issue with how your function is loaded. If you've defined it in a profile script, make sure you've updated that script properly. Functions need to be reloaded in the environment to pick up recent changes. Just a thought!
I noticed you've got a lot of duplicated filtering on DistinguishedName that could be simplified. Also, consider moving your LastLogonDate check into the `-Filter` parameter for better performance, and account for nulls in LastLogonDate to avoid inconsistency in your results.
Have you considered modifying the type casting in your Where-Object? You could try changing it from `Where-Object {($_.LastLogonDate -le (Get-Date).AddDays(-90))}` to `Where-Object {([DateTime]$_.LastLogonDate -le (Get-Date).AddDays(-90))}`. This might help with the comparison based on type.
That's a great tip! Alternatively, you could move the `Get-Date` function to the left side, so it clearly defines the type for the comparison. This way, it looks like: `Where-Object {((Get-Date).AddDays(-90) -ge $_.LastLogonDate)}`.