Search code examples
powershelldsc

How to create a custom DSC resource with MOF


I'm trying to create a custom DSC resource using MOF, as per the instructions here: https://msdn.microsoft.com/en-us/powershell/dsc/authoringresourcemof. I've created the 3 files described and put them in C:\Program Files\WindowsPowerShell\Modules\MyDscResources\DSCResources\MyCustomResource

Import-DscResource appears to work ok, but when I try to use it in a node, it says it is undefined.

Configuration MyServerConfig
{
    Import-DscResource -ModuleName 'MyCustomResource' # this line succeeds

    Node MyServer
    {
        MyCustomResource MyCustomResource  # this line fails
        {
           Ensure = "Present"
           # ...
        }
    }
}

Results in:

Undefined DSC resource 'MyCustomResource'. Use Import-DSCResource to import the resource.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ResourceNotDefined

Is there any way I can get more useful error information to figure out what's wrong with my custom resource?


Solution

  • Instead of trying to create the resource by hand, the solution was to use xDSCResourceDesigner to generate all the files, as per this article http://www.powershellmagazine.com/2015/07/02/creating-a-simple-dsc-resource/

    New-Item -Path "$env:ProgramFiles\WindowsPowerShell\Modules" -Name MyDSCResources -ItemType Directory
    New-ModuleManifest -Path "$env:ProgramFiles\WindowsPowerShell\Modules\MyDSCResources\MyDSCResources.psd1" -Guid (([guid]::NewGuid()).Guid) -Author 'Me' -ModuleVersion 1.0 -Description 'My DSC Resource Module' -PowerShellVersion 4.0 -FunctionsToExport '*.TargetResource'
    
    $Name = New-xDscResourceProperty -Type String -Name Name -Attribute Key
    $Ensure = New-xDscResourceProperty -Name Ensure -Type String -Attribute Write -ValidateSet "Present", "Absent"
    #... more properties
    
    New-xDscResource -Name MyCustomResource -Property $Name,$Ensure -Path "$env:ProgramFiles\WindowsPowerShell\Modules\MyDSCResources" -ClassVersion 1.0 -FriendlyName MyCustomResource –Force
    

    It seems there are a lot of fiddly settings to get right, and not enough error messages to guide you, so not worth doing by hand if you're new to DSC.

    Thanks to @Nana for pushing me in the right direction.