Powershell: using datetime

So let’s assume that in previous code I’ve pulled a list of all users and groups and now want to run some code daily to get new users and groups. You don’t want to pull the whole list every day, as this would get a little unwieldy. But if you just want to know what in AD has changed in the past day or past week or whatever, this is a handy snippet of code that can get you there.

Datetime is always a little tricky to manipulate, but it’s very powerful if you want to do comparisons.

$dayEnd = [datetime]::Today
$dayStart = $dayEnd.AddDays(-1)
foreach ($item in $(get-distributiongroup -resultsize unlimited|where-object {$_.whencreated -ge $daystart -and $_.whencreated -lt $dayend})){$results+=$item.name}

  • $dayEnd = [datetime]::Today <== Here I’m just creating a new variable and want to set it to datetime. But specifying [datetime]::Today I’m telling it just give me monthy, day and year, so it would set the variable to 02262013 00:00:00, for example. Handy since I don’t want it to give a time of NOW.
  • $dayStart = $dayEnd.Adddays(-1) <== So take the previous variable and subtract 1 day from it (i.e. if $dayEnd was 02262013 00:00:00, $dayStart would be 02252013 00:00:00). If you wanted it to add 3 days to the starting variable you’d just do .Adddays(3). A minus sign is a negative here, obviously. So if you wanted the last week you’d do .Adddays (-7).  If you didn’t care about comparing the 2 dates you could also set the initial variable to $day=[datetime]::Today.AddDays(-7) to set $day to a week ago
  • $results=@() <== Create and set an array into a variable
  • get-distributiongroup -resultsize unlimited|where-object {$_.whencreated -ge $daystart -and $_.whencreated -lt $dayend} <== I tried doing a -filter, but that didn’t work correctly, so doing a  pipe into a where clause and key off of whencreated and greater than or equal to the $daystart and less than the $dayend.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s