Cody Whittaker
Cody Whittaker

Reputation: 3

PowerShell: Get-AdUser to variable then filter further to another variable

I know this is simple and can't think of the correct way to do it, and struggling to get the words into google to get the correct answer. I am running Get-AdUser once with a filter of enabled users only further in what I am setting up I need to filter it further but do not want to run the Get-AdUser again.

$users = get-aduser -filter * -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress, LockedOut | where {$_.Enabled -eq "True"} 
$pwUsers = get-aduser -filter * -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress, LockedOut | where {$_.Enabled -eq "True"} | where { $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false }

This is what is currently working for now. I want to be able to do something like this

$pwUsers = $users | where { $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false }

this does not actually filter anything out

Tried using select-object and that just makes $pwUsers = false over and over

Upvotes: 0

Views: 375

Answers (2)

leafy911
leafy911

Reputation: 66

I would do this a different way which would make it easier to manage. When you are handling a large collection of data it is more efficient to filter from the left of the command line which reduces the amount of work that the next command needs to handle. So first set up a variable for the filter:

$filter1 = 'Enabled -eq $true'

We can also setup the properties the same way to reduce what is returned:

$props = @('Name', 'PasswordNeverExpires', 'PasswordExpired', 'PasswordLastSet', 'EmailAddress', 'LockedOut')

Now we can do the following:

$users = get-aduser -filter $filter1 -properties $props | select $props
$pwusers = $users | where {$_.PasswordNeverExpires -eq $false -and $_.PasswordExpired -eq $false}

The select statement would not work here as you are telling select to output a heading of "$_.PasswordNeverExpires -eq $false" with false for every entry

Upvotes: 0

050
050

Reputation: 91

Let's approach your question, first. I understand you want to avoid calling up two get-aduser. You are getting it right, but you should try this:

$pwUsers = $users | Where-Object { $_.PasswordNeverExpires -eq $false } | Where-Object { $_.passwordexpired -eq $false }

Moreover, I recommend you to filter by "Enabled -eq 'True'". Much faster than calling all users and then filtering with where.

Upvotes: 0

Related Questions