get-targetresource

I’ve used the examples in DSC Wave 6 (http://blogs.msdn.com/b/powershell/archive/2014/08/20/dsc-resource-kit-wave-6-is-here.aspx) and trying to create a custom DSC-Resource. Here I have one fundamental question about the 3 default functions (get/set/test-targetresource)

In the get-targetresource, I’m reading out all the current values of the system. Can I then in the Test-targetresource not just call “get-targetresource” and I’m getting back the hashtable with all the current values? I’ve never seen this before in any example. Everyone is reading out the values again in “test-targetresource”, WHY??

I would imagine that efficiency plays a part. In Test-TargetResource, you can just abort the function and return $false anytime you find anything wrong, instead of having to continue reading the rest of the state of the system. (The DSC equivalent of short-circuit evaluation.)

However, you have a point that any Test-TargetResource method could be implemented like this pseudo code:

function Test-TargetResource($desiredState)
{
    $currentState = Get-TargetResource $desiredState.KeyProperties
    return ($currentState -eq $desiredState)
}

The actual code would look a bit different, but you get the idea.

It’s a formatting thing :slight_smile:

In a test-targetresource DSC is looking for a $true $false return, nothing more nothing less. In a get-targetresource it’s actually looking for all the values to be returned. So you can make one call the other and cut your code down, but you’ll have to have some kind of parameter put in place so that the expected data is returned.

If you look at The MSFT_xIPAddress resource in the xNetworking module you’ll see they did this for set-TargetResource and test-TargetResource. They just made a 4th function called “validateproperties” and put an “apply” parameter. It basically either returns $true/$false or makes the changes depending on if the function has -apply appended. You could extend this for the get-targetresource … just make sure you know what data is expected back and format accordingly. Perhaps something like:

if($get) {
$returnvalue = @ {
    value1 = random
    value2 = things
    value3 = here
    }
$returnvalue
}
if($test) {
    switch ($everythingOK) {
    success {return $true}
    fail {return $false}
    }
}

Honestly though after awhile it gets very confusing … so I just tend to leave the get-targetresource function separate from the other two.

Separation of logic, pure and simple. You don’t want the Test- function to be dependent on the Get- function.

What I typically do is create a separate helper function for getting current values, then use that function in both Get- and Test-. Besides Get- is very picky about the formatting of its return data, and it’s not always easy to work with what it outputs.