For a clearer picture

Part 1 – PowerShell Monitors – The Script

This question came up on the TechNet forums and it raised some interesting questions about using PowerShell in a monitor.

Some standard best practice I would look to follow would be:
1. The script should always have some level of error checking along the lines of Try \ Catch \ Finally.

2. I like to include a debug section so that I can set an override to enable debugging which will then output more detailed information when the script is run.

3. I like my PowerShell script just to collect data. I don’t want to be evaluating health states as this hard codes the details into the scripts and doesn’t expose them as overrides. It is much more convenient to do the evaluation of health states in the condition detection and subsequent write action.

I’ll take this in stages with this stage to include the PowerShell script and then how to update it to work within SCOM.

PowerShell script to count the number of folders in a specified folder

So let’s take a look at a PowerShell script to count the number of folders in a folder. I’ve not done a recursive search here but that could be easily achieved with some due care and consideration to the additional performance impact it will have.

Here is the code – https://raw.githubusercontent.com/f1point2/PowerShell/master/Folders/folderCount.ps1

Update the PowerShell script to run in SCOM

To make this usable in SCOM, we need to update it.

Here is the code – https://raw.githubusercontent.com/f1point2/PowerShell/master/Folders/folderCountSCOM.ps1

We instantiate the MOM.ScriptAPI object

And create a Property Bag for which to pass property values back to SCOM.

If you run this on a computer without the SCOM agent installed it will fail. Then again, if you try and run this on a machine with a SCOM agent installed then you won’t get a useful output.

To get some useful output to the screen; what you need to do is comment out the $Bag in the Finally section and replace it with $API.Return($Bag) – this is the way we return VBScript.


# $Bag
$API.Return($Bag)

This provides us with XML output from which we can verify that the script is working as expected.

Once we are happy with the script; make sure to remove the $API.Return($Bag) command and remove the comment from $Bag.


Leave a Reply

Your email address will not be published. Required fields are marked *