[置顶] [16]Windows PowerShell DSC学习系列---基于Class风格定制DSC资源?

标签: PowerShellDSCCustom DSC定制DSC
1519人阅读 评论(0) 收藏 举报
分类:

前面的章节介绍了,[15]Windows PowerShell DSC学习系列---基于.NET DLL(C#) 定制DSC资源?
[11] Windows PowerShell DSC学习系列---如何定制一个基于PowerShell脚本实现的DSC Resource,这一节来的更奇妙的;我们知道根据我们以往的经验,一个开发平台或者一个开发语言,随着版本的更新和发展,其提供的功能会变得越来越强大,越来越方便简单;DSC框架也不例外,在PowerShell DSC 5.0的版本开始,其提供了更多简单的DSC 资源的定制方式,也更加灵活了;其可以让开发者直接编写基于面向对象的类的方式去定制DSC的资源,而且其文件结构也更为简单,已经不需要一定放在DSCResource子文件夹下了。也不需要MOF文件去定义其Schema了,因为其输入参数可以合并到DSC实现类里面一起定义。

本文参考https://msdn.microsoft.com/en-us/powershell/dsc/authoringresourceclass,下面简单介绍一下其具体的实施步骤。

笔者以一个简单的文件拷贝的DSC资源为例子。文件结构如下:


@编写基于DSC Class风格的MyDscResource.psm1的实现

enum Ensure
{
    Absent
    Present
}

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

[DscResource()]
class FileResource
{
    <#
       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 defines the fully qualified path to a file that will
       be placed on the system if $Ensure = Present and $Path does not
        exist.

       NOTE: This property is required because [DscProperty(Mandatory)] is
        set.
    #>
    [DscProperty(Mandatory)]
    [string] $SourcePath

    <#
       This property reports the file's create timestamp.

       [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)]
    [Nullable[datetime]] $CreationTime

    <#
        This method is equivalent of the Set-TargetResource script function.
        It sets the resource to the desired state.
    #>
    [void] Set()
    {
        Write-Verbose -Message "11111111----Begin to invoke Set()------11111111"
        $fileExists = $this.TestFilePath($this.Path)
        if ($this.ensure -eq [Ensure]::Present)
        {
            if (-not $fileExists)
            {
                $this.CopyFile()
            }
        }
        else
        {
            if ($fileExists)
            {
                Write-Verbose -Message "Deleting the file $($this.Path)"
                Remove-Item -LiteralPath $this.Path -Force
            }
        }
        Write-Verbose -Message "11111111----End to invoke Set()------11111111"
    }

    <#
        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()
    {
        Write-Verbose -Message "11111111----Begin to invoke Test()------11111111"
        $present = $this.TestFilePath($this.Path)

        if ($this.Ensure -eq [Ensure]::Present)
        {
           Write-Verbose -Message "11111111----End to invoke Test()------11111111:$present"
            return $present
        }
        else
        {
             Write-Verbose -Message "11111111----End to invoke Test()------11111111:$present"
            return -not $present
        }
        
    }

    <#
        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.
    #>
    [FileResource] Get()

    {
         Write-Verbose -Message "11111111----Begin to invoke Get()------11111111"
        $present = $this.TestFilePath($this.Path)

        if ($present)
        {
            $file = Get-ChildItem -LiteralPath $this.Path
            $this.CreationTime = $file.CreationTime
            $this.Ensure = [Ensure]::Present
        }
        else
        {
            $this.CreationTime = $null
            $this.Ensure = [Ensure]::Absent
        }
         Write-Verbose -Message "11111111----End to invoke Get()------11111111"
        return $this
    }

    <#
        Helper method to check if the file exists and it is file
    #>
    [bool] TestFilePath([string] $location)
    {
        $present = $true

        $item = Get-ChildItem -LiteralPath $location -ea Ignore
        if ($item -eq $null)
        {
            $present = $false
        }
        elseif ($item.PSProvider.Name -ne "FileSystem")
        {
            throw "Path $($location) is not a file path."
        }
        elseif ($item.PSIsContainer)
        {
            throw "Path $($location) is a directory path."
        }

        return $present
    }

    <#
        Helper method to copy file from source to path
    #>
    [void] CopyFile()
    {
        if (-not $this.TestFilePath($this.SourcePath))
        {
            throw "SourcePath $($this.SourcePath) is not found."
        }

        [System.IO.FileInfo] $destFileInfo = new-object System.IO.FileInfo($this.Path)
        if (-not $destFileInfo.Directory.Exists)
        {
            Write-Verbose -Message "Creating directory $($destFileInfo.Directory.FullName)"

            <#
                Use CreateDirectory instead of New-Item to avoid code
                 to handle the non-terminating error
            #>
            [System.IO.Directory]::CreateDirectory($destFileInfo.Directory.FullName)
        }

        if (Test-Path -LiteralPath $this.Path -PathType Container)
        {
            throw "Path $($this.Path) is a directory path"
        }

        Write-Verbose -Message "Copying $($this.SourcePath) to $($this.Path)"

        # DSC engine catches and reports any error that occurs
        Copy-Item -LiteralPath $this.SourcePath -Destination $this.Path -Force
    }
} # This module defines a class for a DSC "FileResource" provider.


@编写MyDscResource的资源模块描述文件

@{
# Script module or binary module file associated with this manifest.
RootModule = 'MyDscResource.psm1'
DscResourcesToExport = 'FileResource'
# Version number of this module.
ModuleVersion = '1.0.1'
# ID used to uniquely identify this module
GUID = '81624038-5e71-40f8-8905-b1a87afe22d7'
# Author of this module
Author = 'Microsoft Corporation'
# Company or vendor of this module
CompanyName = 'Microsoft Corporation'
# Copyright statement for this module
Copyright = '(c) 2014 Microsoft. All rights reserved.'
# Description of the functionality provided by this module
# Description = ''
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '5.0'
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
}

@确认定制资源十分生效

在PowerShell控制台,运行get-dscResource,可以看到起已经生效。


@运行测试文件

测试文件TestFileResouce的PowerShell脚本如下:
Configuration TestFileResource
{
    Import-DSCResource -module MyDscResource
    FileResource file
    {
        Path = "d:\dsc\vvvv.txt"
        SourcePath = "d:\dsc\1111.txt"
        Ensure = "Present"
    } 
}
TestFileResource
Start-DscConfiguration  -Wait -Force -verbose TestFileResource

其输出结果如下,命令运行成功~!!!:
PS D:\DSC> Start-DscConfiguration  -Wait -Force -verbose TestFileResource
VERBOSE: Perform operation 'Invoke CimMethod' with following parameters, ''methodName' = SendConfigurationApply,'className' = MSFT_DSCLocalConfigurationManager,'namespaceName' = root
/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: An LCM method call arrived from computer example-test with user sid S-1-5-21-1801674531-602162358-2146502713-16690.
VERBOSE: [example-test]: LCM:  [ Start  Set      ]
VERBOSE: [example-test]:                            [DSCEngine] Importing the module C:\Program Files\WindowsPowerShell\Modules\MyDscResource\MyDscResource.psd1 in force mode.
VERBOSE: [example-test]: LCM:  [ Start  Resource ]  [[FileResource]file]
VERBOSE: [example-test]: LCM:  [ Start  Test     ]  [[FileResource]file]
VERBOSE: [example-test]:                            [[FileResource]file] Importing the module MyDscResource in force mode.
VERBOSE: [example-test]:                            [[FileResource]file] 11111111----Begin to invoke Test()------11111111
VERBOSE: [example-test]:                            [[FileResource]file] 11111111----End to invoke Test()------11111111:False
VERBOSE: [example-test]: LCM:  [ End    Test     ]  [[FileResource]file]  in 0.0360 seconds.
VERBOSE: [example-test]: LCM:  [ Start  Set      ]  [[FileResource]file]
VERBOSE: [example-test]:                            [[FileResource]file] Importing the module MyDscResource in force mode.
VERBOSE: [example-test]:                            [[FileResource]file] 11111111----Begin to invoke Set()------11111111
VERBOSE: [example-test]:                            [[FileResource]file] Copying d:\dsc\1111.txt to d:\dsc\vvvv.txt
VERBOSE: [example-test]:                            [[FileResource]file] 11111111----End to invoke Set()------11111111
VERBOSE: [example-test]: LCM:  [ End    Set      ]  [[FileResource]file]  in 0.0400 seconds.
VERBOSE: [example-test]: LCM:  [ End    Resource ]  [[FileResource]file]
VERBOSE: [example-test]: LCM:  [ End    Set      ]
VERBOSE: [example-test]: LCM:  [ End    Set      ]    in  0.1280 seconds.
VERBOSE: Operation 'Invoke CimMethod' complete.
VERBOSE: Time taken for configuration job to complete is 0.168 seconds

如果想Debug,请运行Enable-DscDebug -BreakAll
如果想取消DSC的资源的Debug,请运行Disable-DscDebug




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:386273次
    • 积分:6353
    • 等级:
    • 排名:第4108名
    • 原创:228篇
    • 转载:0篇
    • 译文:5篇
    • 评论:157条
    博客专栏