0

I am trying to get a list of properties of AD user objects. Most of the script works except the "where-object" filters are applied. I want to get all users who meet the following: LastLogonDate is more than 75 days ago (this works), enabled (this works) AND either of the following - account expires in the future or never expires. $when is defined properly.

I've tried a number of options and I typically get no output or one or the other in the output.

| Where-Object{($_.lastlogondate -le $When -AND $_.enabled -eq $True) -AND Where-Object($_.AccountExpirationDate -gt (Get-Date) -OR $_.AccountExpirationDate -eq 0)} |

I should see accounts with expiry dates in the future AND accounts that do not expire, but I'm having problems with the "This AND this AND (this OR this)"

2
  • 1
    you cannot chain Where-Object like that. [grin] you need to either pipe from one tot he next OR use a compound set of criteria in one W-O stage. Commented Jul 31, 2019 at 21:18
  • 1
    also, calling Get-Date in the pipeline like that will slow things down - it gets called once per item. [grin] calc that value before you enter the pipeline. Commented Jul 31, 2019 at 21:21

1 Answer 1

1

The extra Where-Object in your code should throw an error...

    Where-Object {
            $_.lastlogondate -le $When -AND 
            $_.enabled -eq $True -AND 
            ($_.AccountExpirationDate -gt (Get-Date) -OR $_.AccountExpirationDate -eq 0)
    }

This should work if your input is correct.

Sign up to request clarification or add additional context in comments.

2 Comments

This is what I used originally, but it doesn't return accounts that are set to never expire. This returns -enabled = true, -lastlogondate is blank (for some reason I don't understand, since I didn't specify that), and the future account expiration date.
I ended up getting exactly what I needed using $null,what I thought I had used before. Here is what works: Where-Object {$_.enabled -eq $True -AND $_.lastlogondate -le $When -AND ($_.AccountExpirationDate -gt (Get-Date) -OR $_.AccountExpirationDate -eq $null)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.