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

前面的章节介绍了,[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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值