Tinus EngOps Wiki

Logo

OpsaC - Operating as PowerShell code

Links

Home

PowerShell Blog

PowerShell Index

PowerShell Search

Additional Websites

View my GitHub Profile

View my GitHub Gists

View Tinus IT Wiki

View my Photo Website

Desired State Configuration

published: April 7, 2019 author: Tinu tags: PowerShell categories: Configuration-Management


Table of Contents

DSC Resource

Get all resources on the local computer.

The Get-DscResource cmdlet retrieves the Windows PowerShell Desired State Configuration (DSC) resources present on the computer. This cmdlet discovers only the resources installed in the PSModulePath.

Get-DscResource

Name                      ModuleName                  ImplementedAs
----                      ----------                  -------------
Archive                   PSDesiredStateConfiguration    PowerShell
Environment               PSDesiredStateConfiguration    PowerShell
File                                                         Binary
Group                     PSDesiredStateConfiguration    PowerShell
GroupSet                  PSDesiredStateConfiguration     Composite
Log                       PSDesiredStateConfiguration        Binary
Package                   PSDesiredStateConfiguration    PowerShell
PackageManagement         PackageManagement              PowerShell
PackageManagementSource   PackageManagement              PowerShell
ProcessSet                PSDesiredStateConfiguration     Composite
Registry                  PSDesiredStateConfiguration    PowerShell
Script                    PSDesiredStateConfiguration    PowerShell
Service                   PSDesiredStateConfiguration    PowerShell
ServiceSet                PSDesiredStateConfiguration     Composite
SignatureValidation                                          Binary
User                      PSDesiredStateConfiguration    PowerShell
WaitForAll                PSDesiredStateConfiguration    PowerShell
WaitForAny                PSDesiredStateConfiguration    PowerShell
WaitForSome               PSDesiredStateConfiguration    PowerShell
WindowsFeature            PSDesiredStateConfiguration    PowerShell
WindowsFeatureSet         PSDesiredStateConfiguration     Composite
WindowsOptionalFeature    PSDesiredStateConfiguration    PowerShell
WindowsOptionalFeatureSet PSDesiredStateConfiguration     Composite
WindowsPackageCab         PSDesiredStateConfiguration    PowerShell
WindowsProcess            PSDesiredStateConfiguration    PowerShell

Syntax to manage Services

Get-DscResource -Syntax -Name Service

Service [String] #ResourceName
{
    Name = [string]
    [BuiltInAccount = [string]{ LocalService | LocalSystem | NetworkService }]
    [Credential = [PSCredential]]
    [Dependencies = [string[]]]
    [DependsOn = [string[]]]
    [Description = [string]]
    [DisplayName = [string]]
    [Ensure = [string]{ Absent | Present }]
    [Path = [string]]
    [PsDscRunAsCredential = [PSCredential]]
    [StartupType = [string]{ Automatic | Disabled | Manual }]
    [State = [string]{ Running | Stopped }]
}

Example

$params = @{
    Property = @{
        Name           = 'MpsSvc'
        BuiltInAccount = 'LocalService'
        Ensure         = 'Present'
        StartupType    = 'Automatic'
        State          = 'Running'
    }
}

Invoke-DscResource

The Invoke-DscResource cmdlet runs a method of a specified Windows PowerShell Desired State Configuration (DSC) resource.

Before you run this cmdlet, set the refresh mode of the Local Configuration Manager (LCM) to Disabled.

This cmdlet invokes a DSC resource directly, without creating a configuration document.
Using this cmdlet, configuration management products can manage windows by using DSC resources.
This cmdlet also enables debugging of resources when the DSC engine or LCM is running with debugging enabled.

Get Configuration

The Get-Method return an Object.

$params = @{
    ModuleName = 'PSDesiredStateConfiguration'
    Name       = 'Service'
    Property   = @{
        Name   = 'MpsSvc'
    }
}
Invoke-DscResource -Method Get @params

ConfigurationName    :
DependsOn            :
ModuleName           : PSDesiredStateConfiguration
ModuleVersion        : 1.1
PsDscRunAsCredential :
ResourceId           :
SourceInfo           :
BuiltInAccount       : LocalService
Credential           :
Dependencies         : {mpsdrv, bfe}
Description          : Windows Firewall helps protect your computer by preventing unauthorized users from gaining access to your
                       computer through the Internet or a network.
DisplayName          : Windows Firewall
Ensure               :
Name                 : MpsSvc
Path                 : C:\Windows\system32\svchost.exe -k LocalServiceNoNetwork
StartupType          : Automatic
State                : Running
Status               :
PSComputerName       : localhost

Test Configuration

The Test-Method return a boolean.

$params = @{
    ModuleName = 'PSDesiredStateConfiguration'
    Name       = 'Service'
    Property   = @{
        Name   = 'MpsSvc'
        Ensure = 'Present'
    }
}
Invoke-DscResource -Method Test @params

InDesiredState
--------------
True

Set Configuration

The Set-Method set the configuration.

$params = @{
    ModuleName = 'PSDesiredStateConfiguration'
    Name       = 'Service'
    Property   = @{
        Name   = 'MpsSvc'
        Ensure = 'Present'
    }
}
Invoke-DscResource -Method Set @params

RebootRequired
--------------
False

DSC Configurations

You need three steps to run a DSC Configuration. Write a Configuration, Compile the Configuration to MOF-file, Execute Configuration.

Write a Configuration

configuration BasicWebConfiguration{

    Import-DscResource -ModuleName PSDesiredStateConfiguration

    Node 'localhost'{

        WindowsFeature WebServerRole {
            Name   = "Web-Server"
            Ensure = "Present"
        }

        WindowsFeature WebMgmtConsole {
            Name   = "Web-Mgmt-Console"
            Ensure = "Present"
        }

    }

}
BasicWebConfiguration

Compile the Configuration to a MOF-file

To call a configuration, the function must be in global scope (as with any other PowerShell function). You can make this happen either by “dot-sourcing” the script, or by running the configuration script by using F5 or clicking on the Run Script button in the ISE. To dot-source the script, run the command . .\myConfig.ps1 where myConfig.ps1 is the name of the script file that contains your configuration.

. .\DSC-BasicWebConfiguration.ps1
BasicWebConfiguration  -Path C:\MOF\BasicWebConfiguration

Execute the Configuration

Test the current Configuration to the MOS-file.

Test-DSCConfiguration  -Path C:\MOF\BasicWebConfiguration

Apply the Configuration from the MOF-file.

Start-DSCConfiguration -Path C:\MOF\BasicWebConfiguration -verbose -wait

Get the Result of all the configured MOF-files.

Get-DSCConfiguration

Full Example

configuration BasicWebConfiguration{

    param (
        [Parameter(Mandatory = $false)]
        [String]$WebDisk
    )

    Import-DscResource -ModuleName PSDesiredStateConfiguration
    Import-Module WebAdministration

    Node 'localhost'{

        #$WebDisk   = "D:"
        $IISSrvDir = "$($WebDisk)\IIS_Server"
        $WebSite   = "$($IISSrvDir)\Default Web Site"
        $IISLogDir = "$($WebDisk)\IIS_Log"
        $WMSvcDir  = "$($IISLogDir)\wmsvc"

        #region WindowsFeatures
        WindowsFeature WebServerRole {
            Name   = "Web-Server"
            Ensure = "Present"
        }

        WindowsFeature WebRequestMonitor {
            Name   = "Web-Request-Monitor"
            Ensure = "Present"
        }

        WindowsFeature WebAspNet {
            Name   = "Web-Asp-Net"
            Ensure = "Present"
        }

        WindowsFeature WebAspNet45 {
            Name   = "Web-Asp-Net45"
            Ensure = "Present"
        }

        WindowsFeature WebMgmtService {
            Name   = "Web-Mgmt-Service"
            Ensure = "Present"
        }

        WindowsFeature WebWindowsAuth {
            Name   = "Web-Windows-Auth"
            Ensure = "Present"
        }

        WindowsFeature WebMgmtConsole {
            Name   = "Web-Mgmt-Console"
            Ensure = "Present"
        }

        WindowsFeature HTTPRedirection {
            Name   = "Web-Http-Redirect"
            Ensure = "Present"
        }
        #endregion

        #region FileSystem
        File IISServerDirectory {
            Type            = 'Directory'
            DestinationPath = $IISSrvDir
            Ensure          = 'Present'
        }

        File IISLogDirectory {
            Type            = 'Directory'
            DestinationPath = $IISLogDir
            Ensure          = 'Present'
        }

        File DefaultWebSite {
            Type            = 'Directory'
            DestinationPath = $WebSite
            Ensure          = 'Present'
            DependsOn       = "[File]IISServerDirectory"
        }

        File WmsvcPath {
            Type            = 'Directory'
            DestinationPath = $WMSvcDir
            Ensure          = 'Present'
            DependsOn       = "[File]IISLogDirectory"
        }
        #endregion

        #region Scripts
        Script AccessControlListWebDisk {

            TestScript = {
                $acl = Get-Acl -Path 'D:' | select -ExpandProperty Access
                $ret = $null

                #region true
                if(($acl.IdentityReference) -match 'IUSR' -and ($acl.FileSystemRights) -match 'FullControl' -and ($acl.AccessControlType) -match 'Allow'){
                    $ret = $true
                }
                if(($acl.IdentityReference) -match 'IIS_IUSRS' -and ($acl.FileSystemRights) -match 'FullControl' -and ($acl.AccessControlType) -match 'Allow'){
                    $ret = $true
                }
                if(($acl.IdentityReference) -match 'NT Service\WMSVC' -and ($acl.FileSystemRights) -match 'FullControl' -and ($acl.AccessControlType) -match 'Allow'){
                    $ret = $true
                }
                #endregion

                #region false
                if(($acl.IdentityReference) -match 'Users'){
                    $ret = $false
                }
                if(($acl.IdentityReference) -match 'Everyone'){
                    $ret = $false
                }
                if(($acl.IdentityReference) -match 'CREATOR OWNER'){
                    $ret = $false
                }
                #endregion

                $ret
            }

            SetScript = {
                cacls 'D:' /E /R Users "CREATOR OWNER" Everyone
                cacls 'D:' /E /G IUSR:R IIS_IUSRS:R "NT Service\WMSVC:F"
            }

            GetScript = {
                $acl = $null
                Get-Acl -Path 'D:' | select -ExpandProperty Access | ForEach {
                    $acl = "$($_.IdentityReference) $($acl)"
                }
                @{
                    GetScript  = 'Get-Acl'
                    Result     = $($acl)
                }
            }

        }

        Script ConfigureIisLogging {

            TestScript = {
                $ret = Get-WebConfigurationProperty -filter "/system.applicationHost/sites/siteDefaults" -name logfile.directory
                if($ret.Value -match $IISLogDir){$true}else{$false}
            }
            SetScript = {
                Set-WebConfigurationProperty "/system.applicationHost/sites/siteDefaults" -name logfile.directory -value $IISLogDir
            }
            GetScript = {
                $ret = Get-WebConfigurationProperty -filter "/system.applicationHost/sites/siteDefaults" -name logfile.directory
                @{
                    GetScript  = 'Get-IISLogDirectory'
                    Result     = "IISLogDirectory: $($ret.Value)" 
                }
            }

        }
        #endregion
    }

}

BasicWebConfiguration -WebDisk 'D:' -OutputPath C:\MOF\BasicWebConfiguration

See also

PSDesiredStateConfiguration on Microsoft Docs


← Previous Post [ Top ] Copyright © 2024 by tinuwalther [ Blog ] Next Post →