Sunday, January 19, 2014

[PowerShell + WMI Eventing ] AD Group Modified --> Run a PowerShell Script

I knew it would be a great learning opportunity when Francois-Xavier Cat Sir agreed to take me in his team for the Winter Scripting Games this year.

FX Sir posted about this great Script which will monitor your AD Group for any changes and then email you the changes if any.
You can find the blog post here

Now while reading the post I had a question...So I did comment on the post there:

Well until recently I found out that it could be done very easily.
So in today's blog post I will show how to trigger a PowerShell Script when a Group in AD is modified.

I got the answer to above question while reading this great book on WMI by Ravi Sir suggested to me by Laerte Junior SirYou can find the book here

If you haven't guessed it by now the answer to making it possible is --- Wait for it "WMI Eventing".

I read this very cool thing on a blog:
                 "The M in WMI stands for Magic"  - Kim Oppalfens

So without further delay let's dive into the stuff.
I have two Scripts in place..doing all this on my Domain Controller:
  •  Dex.ps1 -- Which will create the permanent Event Consumer to monitor the Group.
  • Test.ps1 -- The Script which gets executed when the Event occurs.

To be more precise here the "Event" here is when the changes are made to the AD group (in my example "DexTestGroup") and this event will fire up our script Test.ps1 (for simplicity hardcoded this one).

So below is the Dex.ps1 which will take the Group name as an argument which needs to be monitored of the changes :

Now I have a simple test.ps1 which doesn't do much ...have a look below

The Dex.ps1 creates a Event Filter and then creates a CommandLine Event Consumer and then finally binds those two together......Yeah and it uses CIM Cmdlets which makes life pretty easy.

Yay!! demo time:

I have a test group in my AD by the name "DexTestGroup" and it doesn't have any members yet ....see below:

Now let me setup the monitor for this Group before I do any changes:

All set .....let's add a User to this Group and see what happens:

I have shared this idea with FX Sir and he will soon be incorporating this stuff in his Monitor AD Script ...Monitor his blog for the new version of the Monitor AD Script ;)

This will be really cool as now you won't have to setup a task in Scheduler which runs every minute....Whenever there is a change it will just trigger the Script......awesome !

It is pretty amazing what you can achieve when you start using WMI Eventing...

Try out this can make a lot of changes to the Script on your own and use it.

Let me know if you run into any problems !!