[置顶] [11] Windows PowerShell DSC学习系列---如何定制一个基于PowerShell脚本实现的DSC Resource

标签: PowerShell DSCDevOpsPowerShell定制资源Custom DSC
1111人阅读 评论(0) 收藏 举报
分类:

在这片文章中,笔者给大家分享一个更高级的话题,如何定制一个基于PowerShell脚本实现的DSC Resource,为了简单起见,例子的名称为,Hello World的DSC Resource。因为在Github上提供的定制的DSC的resource有的时候,可能满足不了我们的使用,这个时候,我们就需要做一个定制。下面笔者就分享一个简单的输出Hello World的DSC的resource的步骤。以后,如果时间允许,笔者在和大家一起分享和学习其内部的原理。注意,笔者本机的开发环境是PowerShell DSC 5.1,关于如何安装,请大家参考笔者别的文章。

@第1步 安装xDSCResourceDesigner

我们知道DSC的resource的格式要求比较复杂,不但要定义MOF文件,还要定义MOF Schema,同时还要声明PowerShell的module。工欲善其事,必先利器。那么,有好的工具去屏蔽其复杂性,能够自动生成呢?有的,就是xDSCResourceDesigner。首先通过下面的命令来进行安装。

PS C:\Users\rodney> Install-Module -Name xDSCResourceDesigner

安装之后,我们允许Get-Command -Module xDSCResourceDesigner下面的命令,我们就能看到起提供的函数。

PS C:\Users\rodney> Get-Command -Module xDSCResourceDesigner

CommandType     Name                                                 Version        Source                                                 
-----------     ----                                                                  ------           ------                                                 
Function        Import-xDscSchema                                  1.9.0.0      xDSCResourceDesigner                                   
Function        New-xDscResource                                  1.9.0.0      xDSCResourceDesigner                                   
Function        New-xDscResourceProperty                    1.9.0.0     xDSCResourceDesigner                                   
Function        Test-xDscResource                                   1.9.0.0     xDSCResourceDesigner                                   
Function        Test-xDscSchema                                     1.9.0.0      xDSCResourceDesigner                                   
Function        Update-xDscResource                              1.9.0.0     xDSCResourceDesigner  


@第2步 新建一个PowerShell脚本,编写一个自动生成DSC resource的脚本

脚本的内容如下,文件名字为helloWorldDSC.ps1

$msgProp=New-xDscResourceProperty -Name msg -Type String -Attribute Key
New-xDscResource -ModuleName sayResource -Name SayResource -Property $msgProp -Path 'C:\Program Files\WindowsPowerShell\Modules'

运行上面的脚本,将会在生成下面的文件结构



下面依次打开

#1 C:\Program Files\WindowsPowerShell\Modules\sayResource\SayResource.psd1

#
# Module manifest for module 'sayResource'
#
# Generated by: rodney
#
# Generated on: 2017/2/7
#

@{

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

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

# Supported PSEditions
# CompatiblePSEditions = @()

# ID used to uniquely identify this module
GUID = 'a222c75a-4d61-4342-a4ea-ededace53cda'

# Author of this module
Author = 'rodney'

# Company or vendor of this module
CompanyName = 'Unknown'

# Copyright statement for this module
Copyright = '(c) 2017 rodney. All rights reserved.'

# Description of the functionality provided by this module
# Description = ''

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

# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''

# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''

# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''

# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''

# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''

# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()

# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()

# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()

# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()

# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()

# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()

# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @()

# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()

# Variables to export from this module
VariablesToExport = '*'

# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()

# DSC resources to export from this module
# DscResourcesToExport = @()

# List of all modules packaged with this module
# ModuleList = @()

# List of all files packaged with this module
# FileList = @()

# 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 = @()

        # 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

} # End of PrivateData hashtable

# HelpInfo URI of this module
# HelpInfoURI = ''

# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''

}

#2 C:\Program Files\WindowsPowerShell\Modules\sayResource\DSCResources\SayResource\SayResource.psm1

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]
        $msg
    )

    #Write-Verbose "Use this cmdlet to deliver information about command processing."

    #Write-Debug "Use this cmdlet to write debug information while troubleshooting."


    <#
    $returnValue = @{
    msg = [System.String]
    }

    $returnValue
    #>
}


function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]
        $msg
    )

    #Write-Verbose "Use this cmdlet to deliver information about command processing."

    #Write-Debug "Use this cmdlet to write debug information while troubleshooting."

    #Include this line if the resource requires a system reboot.
    #$global:DSCMachineStatus = 1
}


function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]
        $msg
    )

    #Write-Verbose "Use this cmdlet to deliver information about command processing."

    #Write-Debug "Use this cmdlet to write debug information while troubleshooting."


    <#
    $result = [System.Boolean]
    
    $result
    #>
}


Export-ModuleMember -Function *-TargetResource


#3 C:\Program Files\WindowsPowerShell\Modules\sayResource\DSCResources\SayResource\SayResource.schema.mof

[ClassVersion("1.0.0.0"), FriendlyName("SayResource")]
class SayResource : OMI_BaseResource
{
    [Key] String msg;
};



@第3步 修改SayResource.psm1文件

#1 在 Set-TargetResource函数中加上一行 Write-Verbose $msg

function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]
        $msg
    )
    #Write-Verbose "Use this cmdlet to deliver information about command processing."
    #Write-Debug "Use this cmdlet to write debug information while troubleshooting."
    #Include this line if the resource requires a system reboot.
    #$global:DSCMachineStatus = 1
   try{
       Write-Verbose $msg
   }
   catch {
       $exception = $_
       Write-Verbose "Error occurred while executing Test-TargetResource function"
      if ($exception.InnerException -ne $null)
      {
        $exception = $exception.InnerException
        Write-Verbose $exception.message
     }
  }
    return $false
}
}

#2 在 Test-TargetResource函数中加上一行返回值 $false


function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]
        $msg
    )

    #Write-Verbose "Use this cmdlet to deliver information about command processing."
    #Write-Debug "Use this cmdlet to write debug information while troubleshooting."
    <#
    $result = [System.Boolean]
    $result
    #>
    $false
}

@第4步 测试SayResource DSC resource

编写一个测试的configuration文件,名字为Test.ps1
Configuration Test
{
   Import-DscResource -ModuleName SayResource
   SayResource Hello{
       msg="Hello World,DSC"   
   }
} 
Test
Start-DscConfiguration -Wait -Verbose -Path .\Test

运行Test.ps1,则可以看到SayHello的DSC resource已经生效。




恭喜你,运行成功。但是需要注意的是,如果这个时候在去修改DSC的Resouce中function Set-TargetResource的逻辑时,新的定制的DSC的resource不会马上生效。因为其在DSC 执行引擎中有缓存,如果需要让其生效,需要重启DSC的执行引擎。




1
0

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