Help

I have the current power shell that works to add users to groups based on the condition that they are in a city and department. What I’d like to do is expand on that to filter down to only users who’s accounts are older than 90 days. Can anyone help?

get-aduser -filter{city -eq “City” -And department -eq “Whatever” -Or department -eq “Whatever2” } -SearchBase “MY OU INFO” | %{Add-ADGroupMember “Always” $_.SamAccountName}

First off, what exactly do you mean by “older than 90 days”? That could be creation date, last logon date, last password change, etc. So for argument’s sake lets go with creation date. Since that property is a datetimeobject, we can subtract it from the current date to get the age:

$age = ($(get-date) - $user.whencreated).days

probably the easiest way to do that is with the where-object cmdlet. Before you pipe the get-aduser output over to the add-adgroupmember cmdlet, instead pipe it over to where-object first like so:

get-aduser -properties whencreated -filter{city -eq "City" -And department -eq "Whatever" -Or department -eq "Whatever2" } -SearchBase "MY OU INFO" | where-object{($(get-date) - $_.whencreated).days -ge 90} | %{Add-ADGroupMember "Always" $_.SamAccountName}

Are you sure get-date can subtract from when created. They are in a different date format.

Example:
whencreated : 10/27/2017 4:06:14 PM

PS C:\Windows\system32> Get-Date

Wednesday, November 1, 2017 7:42:38 AM

I think I could use get-date -format d to get them to match up. But I am still not sure where I would insert the 90 days into all of it.

Yep, that’s one of the great things about powershell. While both of those values look different they’re both objects of the type DateTime. So behind the scenes they are structured the same, and powershell knows exactly what to do when you do things like subtraction and addition. Do this real quick to create a couple of test variables.

$CreationDate = get-aduser testuser -properties whencreated | select -expandproperty whencreated
$CurrentDate = get-date

Now you’ll probably see that they look similar. But more importantly if you run these commands you’ll see they both contain all the same properties.

$creationdate | format-list *
$CurrentDate | format-list *

All the formatting stuff is really just for your eyeballs. Powershell still maintains the complete unformatted object for other operations. Now as for getting the days, what we’re doing when we subtract one date from the other is having powershell create a new object of type TimeSpan. To addon to the above example, run this:

$timespan = $currentdate - $creationdate
$timespan | format-list *

So there you can see all the properties of the timespan object. One of those properties is days, which we can reference like any object property

$timespan.days

And that value is just an integer count of the number of days between the two date objects in the beginning example, so you can do your standard math operators on that.