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:
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:
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.