Freigeben über


Erstellen einer klassenbasierten DSC-Ressource

Sie können eine DSC-Ressource definieren, indem Sie eine PowerShell-Klasse erstellen. In einer klassenbasierten DSC-Ressource wird das Schema als Eigenschaften der Klasse definiert, die mit Attributen geändert werden können, um den Eigenschaftentyp anzugeben. Die Ressource wird mit den Methoden Get, Set und Test implementiert (gleich den Get-TargetResourceFunktionen , Set-TargetResourceund Test-TargetResource in einer Skriptressource).

In diesem Artikel erstellen wir eine minimale Ressource namens NewFile , die eine Datei in einem angegebenen Pfad verwaltet.

Weitere Informationen zu DSC-Ressourcen finden Sie unter DSC-Ressourcen.

Hinweis

Generische Auflistungen werden in klassenbasierten Ressourcen nicht unterstützt.

Ordnerstruktur für eine Klassenressource

Um eine DSC-Ressource mit einer PowerShell-Klasse zu implementieren, erstellen Sie die folgende Ordnerstruktur. Die Klasse wird in MyDscResource.psm1 und das Modulmanifest in MyDscResource.psd1 definiert.

$env:ProgramFiles\WindowsPowerShell\Modules (folder)
    |- MyDscResource (folder)
        MyDscResource.psm1
        MyDscResource.psd1

Erstellen einer Klasse

Sie verwenden die class Schlüsselwort (keyword), um eine PowerShell-Klasse zu erstellen. Verwenden Sie das DscResource() -Attribut, um anzugeben, dass eine Klasse eine DSC-Ressource ist. Der Name der Klasse ist der Name der DSC-Ressource.

[DscResource()]
class NewFile {
}

Deklarieren von Eigenschaften

Das DSC-Ressourcenschema ist als Eigenschaften der -Klasse definiert. Es wurden die folgenden drei Eigenschaften deklariert.

[DscProperty(Key)]
[string] $path

[DscProperty(Mandatory)]
[ensure] $ensure

[DscProperty()]
[string] $content

[DscProperty(NotConfigurable)]
[MyDscResourceReason[]] $Reasons

Beachten Sie, dass die Eigenschaften durch Attribute geändert werden. Die Attribute haben folgende Bedeutungen:

  • DscProperty(Key) : Die Eigenschaft ist erforderlich. Die Eigenschaft ist ein Schlüssel. Die Werte aller Eigenschaften, die als Schlüssel gekennzeichnet sind, müssen kombiniert werden, um eine Ressource instance innerhalb einer Konfiguration eindeutig zu identifizieren.
  • DscProperty(Mandatory) : Die Eigenschaft ist erforderlich.
  • DscProperty(NotConfigurable) : Die Eigenschaft ist schreibgeschützt. Eigenschaften, die mit diesem Attribut gekennzeichnet sind, können nicht durch eine Konfiguration festgelegt werden, sondern werden von der Get-Methode aufgefüllt.
  • DscProperty(): Die Eigenschaft ist konfigurierbar, aber nicht erforderlich.

Die Eigenschaften Path und SourcePath sind beide Zeichenfolgen. CreationTime ist eine DateTime-Eigenschaft. Die Ensure-Eigenschaft ist ein Enumerationstyp, der wie folgt definiert ist.

enum Ensure {
    Absent
    Present
}

Einbetten von Klassen

Wenn Sie einen neuen Typ mit definierten Eigenschaften einschließen möchten, die Sie in Ihrer DSC-Ressource verwenden können, erstellen Sie wie zuvor beschrieben eine Klasse mit Eigenschaftentypen.

class MyDscResourceReason {
    [DscProperty()]
    [string] $Code

    [DscProperty()]
    [string] $Phrase
}

Hinweis

Die MyDscResourceReason -Klasse wird hier mit dem Namen des Moduls als Präfix deklariert. Sie können eingebetteten Klassen zwar einen beliebigen Namen geben, aber wenn zwei oder mehr Module eine Klasse mit demselben Namen definieren und beide in einer Konfiguration verwendet werden, löst PowerShell eine Ausnahme aus.

Um Ausnahmen zu vermeiden, die durch Namenskonflikte in DSC verursacht werden, stellen Sie den Namen ihrer eingebetteten Klassen den Modulnamen voran. Wenn der Name Ihrer eingebetteten Klasse bereits unwahrscheinlich ist, können Sie ihn ohne Präfix verwenden.

Wenn Ihre DSC-Ressource für die Verwendung mit dem Computerkonfigurationsfeature von Azure Automanage konzipiert ist, stellen Sie immer dem Namen der eingebetteten Klasse, die Sie für die Reasons-Eigenschaft erstellen, voran.

Öffentliche und private Funktionen

Sie können PowerShell-Funktionen in derselben Moduldatei erstellen und in den Methoden der DSC-Ressourcenklasse verwenden. Die Funktionen müssen als Modulmember in der FunctionsToExport-Einstellung des Modulmanifests exportiert werden. Die Skriptblöcke innerhalb dieser Funktionen können nicht exportierte Funktionen aufrufen.

<#
   Public Functions
#>

function Get-File {
    param(
        [ensure]$ensure,

        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]$path,

        [String]$content
    )

    $fileContent        = [MyDscResourceReason]::new()
    $fileContent.code   = 'file:file:content'

    $filePresent        = [MyDscResourceReason]::new()
    $filePresent.code   = 'file:file:path'

    $ensureReturn = 'Absent'

    $fileExists = Test-Path -Path $path -ErrorAction SilentlyContinue

    if ($fileExists) {
        $filePresent.phrase     = @(
            "The file was expected to be: $ensure"
            "The file exists at path: $path"
        ) -join "`n"

        $existingFileContent    = Get-Content $path -Raw
        if ([string]::IsNullOrEmpty($existingFileContent)) {
            $existingFileContent = ''
        }

        if (![string]::IsNullOrEmpty($content)) {
            $content = $content | ConvertTo-SpecialChars
        }

        $fileContent.phrase = @(
            "The file was expected to contain: $content"
            "The file contained: $existingFileContent"
        ) -join "`n"

        if ($content -eq $existingFileContent) {
            $ensureReturn = 'Present'
        }
    } else {
        $filePresent.phrase = @(
            "The file was expected to be: $ensure"
            "The file does not exist at path: $path"
        ) -join "`n"
        $path = 'file not found'
    }

    @{
        Ensure  = $ensureReturn
        Path    = $path
        Content = $existingFileContent
        Reasons = @($filePresent,$fileContent)
    }
}

function Set-File {
    param(
        [ensure]$ensure = "Present",

        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]$path,

        [String]$content
    )

    Remove-Item $path -Force -ErrorAction SilentlyContinue

    if ($ensure -eq "Present") {
        New-Item $path -ItemType File -Force
        if ([ValidateNotNullOrEmpty()]$content) {
            $content | ConvertTo-SpecialChars | Set-Content $path -NoNewline -Force
        }
    }
}

function Test-File {
    param(
        [ensure]$ensure = "Present",

        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]$path,

        [String]$content
    )

    $test = $false
    $get = Get-File @PSBoundParameters

    if ($get.ensure -eq $ensure) {
        $test = $true
    }

    $test
}

<#
   Private Functions
#>

function ConvertTo-SpecialChars {
    param(
        [parameter(Mandatory = $true,ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [string]$string
    )

    $specialChars = @{
        '`n'  = "`n"
        '\\n' = "`n"
        '`r'  = "`r"
        '\\r' = "`r"
        '`t'  = "`t"
        '\\t' = "`t"
    }

    foreach ($char in $specialChars.Keys) {
        $string = $string -replace ($char,$specialChars[$char])
    }

    $string
}

Implementieren der Methoden

Die Methoden Get, Set und Test entsprechen den Get-TargetResourceFunktionen , Set-TargetResourceund Test-TargetResource in einer Skriptressource.

Es empfiehlt sich, die Codemenge innerhalb der Klassenimplementierung zu begrenzen. Verschieben Sie den Großteil des Codes in exportierte Modulfunktionen, die Sie unabhängig testen können.

<#
    This method is equivalent of the Get-TargetResource script function.
    The implementation should use the keys to find appropriate
    Resources. This method returns an instance of this class with the
    updated key properties.
#>
[NewFile] Get() {
    $get = Get-File -ensure $this.ensure -path $this.path -content $this.content
    return $get
}

<#
    This method is equivalent of the Set-TargetResource script function.
    It sets the Resource to the desired state.
#>
[void] Set() {
    $set = Set-File -ensure $this.ensure -path $this.path -content $this.content
}

<#
    This method is equivalent of the Test-TargetResource script
    function. It should return True or False, showing whether the
    Resource is in a desired state.
#>
[bool] Test() {
    $test = Test-File -ensure $this.ensure -path $this.path -content $this.content
    return $test
}

Die vollständige Datei

Die vollständige Klassendatei folgt.

enum ensure {
    Absent
    Present
}

<#
    This class is used within the DSC Resource to standardize how data
    is returned about the compliance details of the machine. Note that
    the class name is prefixed with the module name - this helps prevent
    errors raised when multiple modules with DSC Resources define the
    Reasons property for reporting when they're out-of-state.
#>
class MyDscResourceReason {
    [DscProperty()]
    [string] $Code

    [DscProperty()]
    [string] $Phrase
}

<#
   Public Functions
#>

function Get-File {
    param(
        [ensure]$ensure,

        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]$path,

        [String]$content
    )

    $fileContent        = [MyDscResourceReason]::new()
    $fileContent.code   = 'file:file:content'

    $filePresent        = [MyDscResourceReason]::new()
    $filePresent.code   = 'file:file:path'

    $ensureReturn = 'Absent'

    $fileExists = Test-Path -Path $path -ErrorAction SilentlyContinue

    if ($fileExists) {
        $filePresent.phrase     = @(
            "The file was expected to be: $ensure"
            "The file exists at path: $path"
        ) -join "`n"

        $existingFileContent    = Get-Content $path -Raw

        if ([string]::IsNullOrEmpty($existingFileContent)) {
            $existingFileContent = ''
        }

        if (![string]::IsNullOrEmpty($content)) {
            $content = $content | ConvertTo-SpecialChars
        }

        $fileContent.phrase     = @(
            "The file was expected to contain: $content"
            "The file contained: $existingFileContent"
        ) -join "`n"

        if ($content -eq $existingFileContent) {
            $ensureReturn = 'Present'
        }
    } else {
        $filePresent.phrase     = @(
            "The file was expected to be: $ensure"
            "The file does not exist at path: $path"
        ) -join "`n"
        $path = 'file not found'
    }

    @{
        ensure  = $ensureReturn
        path    = $path
        content = $existingFileContent
        Reasons = @($filePresent,$fileContent)
    }
}

function Set-File {
    param(
        [ensure]$ensure = "Present",

        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]$path,

        [String]$content
    )

    Remove-Item $path -Force -ErrorAction SilentlyContinue

    if ($ensure -eq "Present") {
        New-Item $path -ItemType File -Force
        if ([ValidateNotNullOrEmpty()]$content) {
            $content | ConvertTo-SpecialChars | Set-Content $path -NoNewline -Force
        }
    }
}

function Test-File {
    param(
        [ensure]$ensure = "Present",

        [parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]$path,

        [String]$content
    )

    $test = $false
    $get = Get-File @PSBoundParameters

    if ($get.ensure -eq $ensure) {
        $test = $true
    }

    return $test
}

<#
   Private Functions
#>

function ConvertTo-SpecialChars {
    param(
        [parameter(Mandatory = $true,ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [string]$string
    )
    $specialChars = @{
        '`n'  = "`n"
        '\\n' = "`n"
        '`r'  = "`r"
        '\\r' = "`r"
        '`t'  = "`t"
        '\\t' = "`t"
    }
    foreach ($char in $specialChars.Keys) {
        $string = $string -replace ($char,$specialChars[$char])
    }
    return $string
}

<#
    This Resource manages the file in a specific path.
    [DscResource()] indicates the class is a DSC Resource
#>

[DscResource()]
class NewFile {

    <#
        This property is the fully qualified path to the file that is
        expected to be present or absent.

        The [DscProperty(Key)] attribute indicates the property is a
        key and its value uniquely identifies a Resource instance.
        Defining this attribute also means the property is required
        and DSC will ensure a value is set before calling the Resource.

        A DSC Resource must define at least one key property.
    #>
    [DscProperty(Key)]
    [string] $path

    <#
        This property indicates if the settings should be present or absent
        on the system. For present, the Resource ensures the file pointed
        to by $Path exists. For absent, it ensures the file point to by
        $Path does not exist.

        The [DscProperty(Mandatory)] attribute indicates the property is
        required and DSC will guarantee it is set.

        If Mandatory is not specified or if it is defined as
        Mandatory=$false, the value is not guaranteed to be set when DSC
        calls the Resource.  This is appropriate for optional properties.
    #>
    [DscProperty(Mandatory)]
    [ensure] $ensure

    <#
        This property is optional. When provided, the content of the file
        will be overwridden by this value.
    #>
    [DscProperty()]
    [string] $content

    <#
        This property reports the reasons the machine is or is not compliant.

        [DscProperty(NotConfigurable)] attribute indicates the property is
        not configurable in DSC configuration.  Properties marked this way
        are populated by the Get() method to report additional details
        about the Resource when it is present.
    #>
    [DscProperty(NotConfigurable)]
    [MyDscResourceReason[]] $Reasons

    <#
        This method is equivalent of the Get-TargetResource script function.
        The implementation should use the keys to find appropriate
        Resources. This method returns an instance of this class with the
        updated key properties.
    #>
    [NewFile] Get() {
        $get = Get-File -ensure $this.ensure -path $this.path -content $this.content
        return $get
    }

    <#
        This method is equivalent of the Set-TargetResource script function.
        It sets the Resource to the desired state.
    #>
    [void] Set() {
        $set = Set-File -ensure $this.ensure -path $this.path -content $this.content
    }

    <#
        This method is equivalent of the Test-TargetResource script
        function. It should return True or False, showing whether the
        Resource is in a desired state.
    #>
    [bool] Test() {
        $test = Test-File -ensure $this.ensure -path $this.path -content $this.content
        return $test
    }
}

Erstellen eines Manifests

Um eine klassenbasierte DSC-Ressource verfügbar zu machen, müssen Sie eine DscResourcesToExport -Anweisung in die Manifestdatei einschließen, die das Modul anweist, die DSC-Ressource zu exportieren. Unser Manifest sieht folgendermaßen aus:

@{

    # Script module or binary module file associated with this manifest.
    RootModule = 'NewFile.psm1'

    # Version number of this module.
    ModuleVersion = '1.0.0'

    # ID used to uniquely identify this module
    GUID = 'fad0d04e-65d9-4e87-aa17-39de1d008ee4'

    # Author of this module
    Author = 'Microsoft Corporation'

    # Company or vendor of this module
    CompanyName = 'Microsoft Corporation'

    # Copyright statement for this module
    Copyright = ''

    # Description of the functionality provided by this module
    Description = 'Create and set content of a file'

    # Minimum version of the Windows PowerShell engine required by this module
    PowerShellVersion = '5.0'

    # Functions to export from this module
    FunctionsToExport = @('Get-File','Set-File','Test-File')

    # DSC Resources to export from this module
    DscResourcesToExport = @('NewFile')

    # Private data to pass to the module specified in RootModule/ModuleToProcess.
    # This may also contain a PSData hashtable with additional module metadata used by PowerShell.
    PrivateData = @{

        PSData = @{

            # Tags applied to this module. These help with module discovery in online galleries.
            # Tags = @(Power Plan, Energy, Battery)

            # A URL to the license for this module.
            # LicenseUri = ''

            # A URL to the main website for this project.
            # ProjectUri = ''

            # A URL to an icon representing this module.
            # IconUri = ''

            # ReleaseNotes of this module
            # ReleaseNotes = ''

        } # End of PSData hashtable

    }
}

Testen der Ressource

Nachdem Sie die Klassen- und Manifestdateien in der zuvor beschriebenen Ordnerstruktur gespeichert haben, können Sie eine DSC-Konfiguration erstellen, die die neue DSC-Ressource verwendet. Im Folgenden Configuration wird überprüft, ob die Datei unter /tmp/test.txt vorhanden ist und ob der Inhalt mit der von der Content-Eigenschaft bereitgestellten Zeichenfolge übereinstimmt. Wenn nicht, wird die gesamte Datei geschrieben.

Configuration MyConfig {
    Import-DSCResource -ModuleName NewFile
    NewFile testFile {
        Path = "/tmp/test.txt"
        Content = "DSC Rocks!"
        Ensure = "Present"
    }
}

MyConfig

Deklarieren mehrerer klassenbasierter DSC-Ressourcen in einem Modul

Ein Modul kann mehrere klassenbasierte DSC-Ressourcen definieren. Sie müssen alle Klassen in derselben .psm1 Datei deklarieren und jeden Namen in das .psd1 Manifest einschließen.

$env:ProgramFiles\PowerShell\Modules (folder)
    |- MyDscResource (folder)
        |- MyDscResource.psm1
            MyDscResource.psd1

Weitere Informationen