Testing out PowerShell Desired State Configurations


Tested out PowerShell Desired State Configuration this morning, in this post I’m going step-by-step through my first script using PowerShell Desired State Configuration (DSC). The project is to create a simple website to the Default website in my lab environment, running the Microsoft Internet information Services (IIS) Server.

Setting up the environment – Creating the folder and files

First thing to do is, import the PowerShell Desired State Configuration module to be able to use DSC.

# To use PowerShell's module for DSC, we need to import the module
Import-Module -Name PsDesiredStateConfiguration

# When the module is imported, we can check to see its available with the following command
Get-Module -Name PsDesiredStateConfiguration

# If you want to view all the Cmdlets in the module you can type:
Get-Command -Module "psDesiredStateConfiguration"

# To get all the function in the module, you can type:
Get-Command -Module "psDesiredStateConfiguration" -CommandType Function

Then we need to create the necessary folder and files to get started. I use the command line in PowerShell ISE to create these, and is created by typing the following:

# I've added the folder location to indicate where I'm working.
# First we need a working directory and some files. Info: You can also use mkdir to create directory.
PS C:\Users\Administrator> Set-Location -Path C:\
PS C:\> New-Item -Path .\ -Name ConfigurationTest -ItemType Directory
PS C:\> cd ConfigurationTest
PS C:\ConfigurationTest> New-Item -Path .\ -Name index.htm -ItemType File
PS C:\ConfigurationTest> New-Item -Path .\ -Name Create-TestWebsite.ps1 -ItemType File

# A nifty way to open the  files in ISE is to type:
PS C:\ConfigurationTest> ise index.html
PS C:\ConfigurationTest> ise Create-TestWebsite.ps1

#=================================================================="

# Then the test environment is setup.
# You can copy/paste the commands below (without the specified paths)
# into your PS ISE editor and hit "Run Script (F5)" and you're
# all set to get started.

Set-Location -Path C:\
New-Item -Path .\ -Name ConfigurationTest -ItemType Directory
cd ConfigurationTest
New-Item -Path .\ -Name index.htm -ItemType File
New-Item -Path .\ -Name Create-TestWebsite.ps1 -ItemType File
# A nifty way to open the files in ISE is to type, the files will open in the tabs next to your initial one.
ise index.htm
ise Create-TestWebsite.ps1

Writing the content and configuration

Now, that we have setup our initial folder and files, we need to will these with some code.
Firstly, we fill the index.htm with content we will use as the website.

This is stored in the C:\ConfigurationTest folder we created earlier with the PowerShell cmdlet.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>My first website</title>
</head>
<body>
    <h1>Hello World</h1>
    <p>My first website, using PowerShell Desired State Configuration</p>
</body>
</html>

Secondly, the Desired State Configuration file. A DSC configuration is a special PowerShell function that defines how you want to configure one or more target computers (nodes). The Configuration block is the outermost script block, in this case the name of the configuration is Create-TestWebsite. Using the Verb-Noun naming standard to keeping it consistent.

The file is also stored in the C:\ConfigurationTest folder and the it looks like this:

Configuration Create-TestWebsite {

    # Import the module that contains the resources we're using.
    Import-DscResource -ModuleName PsDesiredStateConfiguration

    # The Node statement specifies which targets this configuration will be applied to.
    Node 'localhost' {

        # The first resource block ensures that the Web-Server (IIS) feature is enabled.
        WindowsFeature WebServer {
            Ensure = "Present"
            Name   = "Web-Server"
        }

        # The second resource block ensures that the website content copied to the website root folder.
        File WebsiteContent {
            Ensure = 'Present'
            SourcePath = 'c:\ConfigurationTest\index.htm'
            DestinationPath = 'c:\inetpub\wwwroot'
        }
    }
}
# Calling the function
Create-TestWebsite

You can see that the code looks like a PowerShell function, with the addition keyword Configuration used before the name of the function. Info: This is the first function that will be listed when running the cmdlet Get-Command -Module psDesiredStateConfiguration

The Node block specifies the target node to be configured, in other words nodes are the endpoint we wish to configure, such as computers and virtual machines (VM’s). A node block can also accept multiple computer names, but in our case we use localhost.This allows us to use the configuration locally on any server.

Furthermore, **Resource blocks is where the configuration sets the properties for the resources. In this case there is two resource blocks called WindowsFeature and File.** This ensures that the target node is in the state defined by the configuration.

Compile the configuration

For a DSC configuration to be applied to a node (Computer or VM), it must first be compiled into a MOF file. To do this, we can run the configuration like a function, in a PowerShell console. By navigating to the same folder we added the configuration file, in our case C:\ConfigurationTest then we need to run the following (Note, this requires elevated privileges):

PS C:\ConfigurationTest>. .\Create-TestWebsite.ps1

# This will return
Directory: C:\ConfigurationTest\Create-TestWebsite

    Mode                LastWriteTime         Length Name
    ----                -------------         ------ ----
    -a----        3/13/2017   5:20 PM           2746 localhost.mof

Note: If you don’t add a function call in the configuration file (Create-TestWebsite.ps1), you can compile the configuration file using dot source to load it into the current scope, then you can call it like a function. As the following example:

# Using dot source to load the function into current scope, then calling the function.
PS C:\ConfigurationTest>. .\Create-TestWebsite.ps1
Create-TestWebsite

Both ways works fine, and result in a new folder, named Create-TestWebsite

is created as a subfolder of the current folder. In the Create-TestWebsite folder a localhost.mof file has been created. This is the file that can then be applied to the target node. Next step is to apply the configuration.

Apply the configuration

Now that the compiled MOF-file is created, the remaining part is to apply the configuration to the target node. In this case the target node is my local computer (or lab VM). This can be done by calling the cmdlet Start-DscConfiguration. This cmdlet tells the Local Configuration Manager (LCM), which is the engine of Desired State Configuration (DSC), and the LCM does the work of calling the DSC resources to apply the configuration. In our case it calls the call the resources WindowsFeature WebServer and File WebsiteContent and applied the properties defined in the resources.

To apply the configuration we need to execute the cmdlet Start-DscConfiguration

and specify the location of the folder where the localhost.mof is stored to the -Path parameter, which looks like this:

PS C:\ConfigurationTest>Start-DscConfiguration -Path PS .\Create-TestWebsite

# Returns
PS C:\ConfigurationTest> Start-DscConfiguration -Path .\Create-TestWebsite

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
2      Job2            Configuratio... Running       True            localhost            Start-DscConfiguration...

What this does is to look through the directory specified for any ComputernameOrVMs.mof files. Then the Start-DSCConfiguration attempts to apply each .mof file it finds to the computer names specified by the filename, for instance (“localhost”, “WSUS-01”, “WEB-01”, “DC-02”) etc.

Next step making sure the configuration was applied correctly.

Testing the configuration

To test if our configuration succeeded we can use the following cmdlet:

PS C:\ConfigurationTest> Get-DscConfigurationStatus

# When the cmdlet is runned, it should return this if successful. Yay!
PS C:\ConfigurationTest> Get-DscConfigurationStatus

Status     StartDate                 Type            Mode  RebootRequested      NumberOfResources
------     ---------                 ----            ----  ---------------      -----------------
Success    16.03.2019 09.22.32       Consistency     PUSH  False                2

Also we can test the result directly by browsing to http://localhost in a web browser. And we should see the awesome HTML page that says “My first website, using PowerShell Desired State Configuration”. Like below:

The result of the Desired State Configurations.

Hurray! It works. Well I guess that’s it hope you enjoyed the post.