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

原创 2017年02月07日 23:36:31

在这片文章中,笔者给大家分享一个更高级的话题,如何定制一个基于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的执行引擎。




版权声明:本文为博主原创文章,未经博主允许不得转载。

[17]Windows PowerShell DSC学习系列---使用WMI Tester调用msft-dsclocalconfigurationmanager类的方法

在这边文章中,其列出了DSC中的本地配置管理引擎中的msft-dsclocalconfigurationmanager类,其列出了这个类中的很多方法。比如GetConfigurationStatus,...

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

前面的章节介绍了,[15]Windows PowerShell DSC学习系列---基于.NET DLL(C#) 定制DSC资源?和 [11] Windows PowerShell DSC学习系列--...

[24]Window PowerShell DSC学习系列---- 如何保护MOF文件里面存储的密码?

在上节笔者分享了[23]Window PowerShell DSC学习系列---- MOF文件能存储用户的密码吗?MOF文件里面能直接存储明文密码,这样是非常不安全的。那么有什么方式能够把MOF里面存...

[23]Window PowerShell DSC学习系列---- MOF文件能存储用户的密码吗?

我们知道,DSC的资源中,有很多的资源是需要访问文件共享目录,进入本地的用户的目录,或者为一个特定的用户安装一个MSI的安装包,修改注册表;这个时候,如果直接执行调用DSC的资源,则可能会弹出“Acc...

[2] Window PowerShell DSC 学习系列----DSC的资源(Resource)以及配置和格式(Configuration && Sytax )

这个章节主要来讲述DSC的资源(Resource)以及配置和格式(Configuration && Sytax )。...

[10] Window PowerShell DSC 学习系列----目标节点和Pull 服务器底层通信原理剖析

在本节中,笔者将会用wireshark抓包,并分析目标节点如何和Pull 服务器通信的?注意笔者本机装的Window Management Framework 5.1,如果是其他的版本,可能请求的UR...

[7] Window PowerShell DSC 学习系列----如何被管理的设置节点注册到Pull Server?

在上一节,[6] Window PowerShell DSC 学习系列----如何安装最新的PowerShell DSC 5.1 Pull Server?笔者聊到了如何安装Pull Server。那么...

[20]Window PowerShell DSC学习系列---- start-dscconfiguration 中遇到 Access Denied的解决方案

当我们执行start-DscConfiguration -computername psdsc-window201 -Path c:\DSC\TestFile -Wait -Verbose -forc...

[26]Window PowerShell DSC学习系列----如何更换Pull服务器数据库为SQL Server数据库

上节我们提到了如何把PowerShell DSC的数据库换成Access;DSC Pull服务器当前的版本对MS SQL Server是不支持的,该怎么办?另外如果我们需要对Pull服务器建立负载均衡...

[9] Window PowerShell DSC 学习系列----错误诊断和分析

PowerShell DSC就像一个汽车,内部复杂,司机作为一个普通的用户在使用它,因为知道一些汽车的基本常识,所以当汽车发生一些简单的故障时,可以通过汽车自身带的仪表仪器诊断问题出在哪方面,也可以借...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:[11] Windows PowerShell DSC学习系列---如何定制一个基于PowerShell脚本实现的DSC Resource
举报原因:
原因补充:

(最多只允许输入30个字)