Simplify your PowerShell DSC Configurations by using parameterized DSC Resources


Often I can see that DSC adopters use similar code:

Configuration TooVerbose
{
    Import-DscResource -ModuleName PSDesiredStateConfiguration

    Service abc
    {
        Name    = 'abc'
        State   = 'Running'
        Ensure  = 'Present'
    }
    Service def
    {
        Name    = 'abc'
        State   = 'Running'
        Ensure  = 'Present'
    }
    Service xyz
    {
        Name    = 'abc'
        State   = 'Running'
        Ensure  = 'Present'
    }
}

The problem is that this is too complex (too verbose) for simple result like for example three services that should run. The proper was is to simplify your code and ensure easy readability and protect yourself against typing errors.

Configuration ServiceRunning
{
    Param
    (
        [string[]]$Name
    )

    Import-DscResource -ModuleName PSDesiredStateConfiguration

    foreach ($nameItem in $name)
    {
        Service ('ServiceRunning{0}' -f $nameItem)
        {
            Name    = $nameItem
            State   = 'Running'
            Ensure  = 'Present'
        }
    }
}

Configuration NiceAndShort
{
    # Looks like a DSC Resource
    ServiceRunning ServiceRunning
    {
        Name = 'abc', 'def', 'xyz'
    }
}

NiceAndShort -OutputPath 'D:\SomePlaceOnYourComputer'

Leave a Reply

Your email address will not be published. Required fields are marked *

Active Directory Advanced function AlwaysOn Availability Groups AlwaysOn Failover Cluster Instances Building Cloud Cloud Cluster Cmdlet Database Deployment Design DFS Domain Controller DSC Fabric Failover Clustering File Server Group Policy Hardware Profile Host Hyper-V Installation Library Library Asset Library Server Network Operations Manager Orchestrator PowerShell PowerShell User Group PowerShell Workflow Security Service Manager SQL Server Storage System Center Template Time Time Synchronization Tips Virtual Machine Virtual Machine Manager VM Network VM Template Windows Server 2012 R2