Problem with variable names starting with “Data”

There is a known bug in SCOM, whereby PowerShell scripts that are embedded in rules or monitors (i.e. where the script is visible in the data source of the rule/monitor) can’t contain references to variables whose names start with Data, e.g. Database. More specifically, such variables can’t be accessed using the dollar notation, e.g. $Database. VSAE will throw an exception when attempting to build a project containing such references:

The configuration specified for Module DS is not valid.
: Incorrect expression specified: $Database
Unable to resolve this expression. Check the expression for errors.

There are two workarounds. The easiest is to simply rename all the affected variables; e.g.:

$Database

to

$_Database

A more complex solution, although it allows the existing variable names to be used, is to change the method of access: using the Set-Variable and Get-Variable cmdlets. For example:

Set-Variable DataSet (New-Object System.Data.DataSet)
Get-Variable DataSet -ValueOnly

Care must be taken, however, to ensure that the value is unboxed; e.g. this will always return a value of 1:

Set-Variable SomeValues (1..5)
(Get-Variable SomeValues -ValueOnly | measure).Count

Instead, to obtain the count, use:

((Get-Variable SomeValues -ValueOnly) | measure).Count