Wednesday, October 22, 2014

Creating a Demo Custom DSC Resource

When creating custom DSC resources sometimes it is handy to isolate an issue into a fresh DSC resource, or simply to experiment quickly without impacting existing progress.

The script below will create a demo DSC resource really quickly, allowing you to put content into the script and test it right away.

I’ve been using this to test something quickly then just throw it away, almost like snippets in PowerShell ISE.


### Demo DSC Custom Resource details

$demoModuleName  = 'DemoModule'

$dscResourceName = 'DemoDscCustomResource'


### Create the new resource

New-xDscResource -Name $dscResourceName -Path "C:\Program Files\WindowsPowerShell\Modules\$demoModuleName" -Property @(

    New-xDscResourceProperty -Name Prop1  -Type String    -Attribute Key

    New-xDscResourceProperty -Name Prop2  -Type String    -Attribute Write

    New-xDscResourceProperty -Name Ensure -Type String    -Attribute Write -ValidateSet "Present", "Absent"



### Convert the generated files to UTF8


"C:\Program Files\WindowsPowerShell\Modules\$demoModuleName\DSCResources\$dscResourceName\$dscResourceName.schema.mof"

"C:\Program Files\WindowsPowerShell\Modules\$demoModuleName\DSCResources\$dscResourceName\$dscResourceName.psm1"

) | ForEach-Object {

    $fileContent = Get-Content $_

    Set-Content -Value $fileContent -Path $_ -Encoding UTF8



### Create an empty PSM1 file for the new module

Set-Content -Value "### Test File" -Path "C:\Program Files\WindowsPowerShell\Modules\$demoModuleName\$demoModuleName.psm1" -Encoding UTF8


### Modify the new DSC custom resource module

psedit  "C:\Program Files\WindowsPowerShell\Modules\$demoModuleName\DSCResources\$dscResourceName\$dscResourceName.psm1"


### Generate a simple test script


Set-Location $HOME


Configuration Test{0}



    Import-DscResource -ModuleName {1}


    Node (hostname)


        {0} Test{0}


            Prop1   = 'foo'

            Prop2   = 'bar'

            Ensure  = 'Present'







Start-DscConfiguration -Wait -Verbose -Debug -Path (Join-Path $Home TestDemoDscCustomResource)


'@ -F $dscResourceName, $demoModuleName  |

Out-File -Encoding utf8 -FilePath "C:\Program Files\WindowsPowerShell\Modules\$demoModuleName\Test-$dscResourceName.ps1"


### Open the new test script

psedit  "C:\Program Files\WindowsPowerShell\Modules\$demoModuleName\Test-$dscResourceName.ps1"


No comments: