20 April 2014

Some time ago I posted a script to remotely enable WinRM on a machine.  I have to admit it was fairly kludgy in that it had a lot of moving parts that had to execute just right.  Registry edits to turn on features, create listener config, modify firewall rules, and then cmdlets to remotely stop and start services.  I even wrote one that tried to rely on setting scheduled tasks with batch scripts (which would also call Powershell scripts) to get the job done…   There are a lot of points of failure in both attempts.

The scheduled tasks didn’t always execute correctly (or even get set to be executed) and I just had a lot of trouble with it.  That’s why I set out to write the second one.  The second one, while still a very inelegant way to do it, was solid except for one point of failure that, well, failed.  It failed almost all of the time because it required too perfect a condition.

Stopping and restarting the Windows Firewall Service remotely is just a bad idea.  If the timing between firing off the stop and start is perfect (i.e. lightning fast) then chances are the start command wont ever make it to the remote.  The reason is because once the Firewall Service is stopped the OS goes into a bit of a lockdown and doesn’t allow incoming communication via things like WMI.  It’s a great safety mechanism against remote attacks but a real pain in the butt when you don’t have time to (or just can’t) go to a machine.  The only other way to do it is locally… but I just said sometimes you can’t get to the local machine.  WinRM is our way to execute things remotely as if we were local… and if it’s not enabled then what is the solution?  There is another way to execute remote commands as if they were local!

Enter the Invoke-WMIMethod cmdlet.  This cmdlet allowed me to greatly improve my success rate and make it very elegant!  It simplifies the script  a great deal and only needs one remote mechanism to function.  My original function was 51 lines long, the second one 35, and now this one is only 18!  It can be reduced more but I have detection and logging in there too.  I’ve adapted it to be a standalone script for sharing here .  Without my monstrous heading (which I hope you’ll keep in tact if you use or share this…) it’s still only 30 lines (which includes several comments).  The one caveat to this script is that in order for it to work, Remote WMI rules in the firewall need to be enabled to allow it through!  I dont believe these are turned on by default (in my company we turn them on, on all PC’s so we can mange them…).

OK, I’ve rambled enough, here’s the script:  EnableWinRM


Thanks to this script for teaching me that the Invoke-WMIMethod was capable of starting a new process:  http://gallery.technet.microsoft.com/scriptcenter/Get-NetworkStatistics-66057d71


There are no comments.

You must be logged in to post a comment.