I've been using variations of this script for going on 3 years now and its always served me very well. The inspiration comes from Corey Harrell who had a similar Perl script.
Since I didn't know Perl and it didn't really suit our environment, I modified his to work in Powershell and now we deploy it via Carbon Black but it can still be used as a stand alone.
Credit for different sections of code are documented in the script.
Lines 30, 77, and 83 need to be adjusted for your environment