0
0
PowerShellscripting~5 mins

Desired State Configuration (DSC) basics in PowerShell

Choose your learning style9 modes available
Introduction
Desired State Configuration (DSC) helps you keep your computer or server set up the way you want it, automatically fixing things if they change.
You want to make sure a software is always installed on your computer.
You want a folder to always exist with certain files inside.
You want to keep a service running and restart it if it stops.
You want to set network settings the same way on many computers.
You want to automate setup tasks so you don't do them by hand every time.
Syntax
PowerShell
Configuration ConfigName {
    Node 'localhost' {
        ResourceName ResourceType {
            Property1 = 'Value1'
            Property2 = 'Value2'
        }
    }
}

ConfigName
Start-DscConfiguration -Path ./ConfigName -Wait -Verbose
A Configuration block defines the desired setup using resources.
Node specifies which computer(s) the configuration applies to.
Examples
This example ensures a folder named C:\Example exists on your computer.
PowerShell
Configuration SampleConfig {
    Node 'localhost' {
        File ExampleFolder {
            DestinationPath = 'C:\Example'
            Type = 'Directory'
            Ensure = 'Present'
        }
    }
}

SampleConfig
Start-DscConfiguration -Path ./SampleConfig -Wait -Verbose
This example installs Notepad++ if it is not already installed.
PowerShell
Configuration InstallNotepadPlusPlus {
    Node 'localhost' {
        Package NotepadPlusPlus {
            Name = 'Notepad++'
            Path = 'C:\Installers\npp.8.5.2.Installer.exe'
            ProductId = ''
            Ensure = 'Present'
        }
    }
}

InstallNotepadPlusPlus
Start-DscConfiguration -Path ./InstallNotepadPlusPlus -Wait -Verbose
Sample Program
This script creates a configuration named EnsureFolder that makes sure the folder C:\MyFolder exists. Then it applies the configuration immediately.
PowerShell
Configuration EnsureFolder {
    Node 'localhost' {
        File MyFolder {
            DestinationPath = 'C:\MyFolder'
            Type = 'Directory'
            Ensure = 'Present'
        }
    }
}

EnsureFolder
Start-DscConfiguration -Path ./EnsureFolder -Wait -Verbose
OutputSuccess
Important Notes
DSC uses resources like File, Package, Service to define what you want on your machine.
You run the configuration function first to create files, then apply them with Start-DscConfiguration.
Use -Wait and -Verbose to see progress and wait until the setup finishes.
Summary
DSC helps keep your computer setup the way you want automatically.
You write a Configuration block with resources describing your desired setup.
Run the configuration and then apply it to enforce the desired state.