5.PowerShell DSC核心概念之资源

什么是资源?

资源为 DSC 配置提供构建基块。

资源公开可配置的属性,并包含本地配置管理器 (LCM) 调用以“使其如此”的 PowerShell 脚本函数。

系统内置资源

可在PowerShell命令窗中输入Get-DSCResource查看系统内置的资源
(在命令窗中输入命令的时候,可使用tab键进行补全提示)

image

我们可以看到内置了一些常用的资源,比如File、User等

第三资源

系统内置的资源很可能不能满足我们的需求,我们可以在公共的hub中下载,地址:https://www.powershellgallery.com/

image

其实这东西和nuget(https://www.nuget.org/)非常的相似,你也可以自己写资源上传,供大家下载使用。

自定义资源

有些时候,系统内置的资源和第三方资源仍然不满足我们的需求,就需要根据具体的业务进行定制资源。

首先需要明白一点:PowerShell DSC配置是围绕 Get 、Test 和 Set 构建的。

以下我们使用基于 MOF 编写自定义 DSC 资源

文件夹结构

$env:ProgramFilesWindowsPowerShellModules (folder)
    |- MyDscResources (folder)
        |- DSCResources (folder)
            |- Demo_IISWebsite (folder)
                |- Demo_IISWebsite.psd1 (file, optional)
                |- Demo_IISWebsite.psm1 (file, required)
                |- Demo_IISWebsite.schema.mof (file, required)

.schema.mof 编写

简单来讲,就是定义当前资源的参数

[ClassVersion("1.0.0"), FriendlyName("Website")]
class Demo_IISWebsite : OMI_BaseResource
{
  [Key] string Name;
  [Required] string PhysicalPath;
  [write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] string Ensure;
  [write,ValueMap{"Started","Stopped"},Values{"Started", "Stopped"}] string State;
  [write] string Protocol[];
  [write] string BindingInfo[];
  [write] string ApplicationPool;
  [read] string ID;
};

.psm1文件编写

资源脚本实现资源的逻辑。 此模块中必须包含三个函数,名称如下:

function Get-TargetResource{
    //todo
}
function Set-TargetResource{
    //todo
}
function Test-TargetResource{
    //todo
}

.psd1文件编写

@{
    ModuleVersion = '1.0'
    GUID = '6AB5ED33-E923-41d8-A3A4-5ADDA2B301DE'
    Author = 'Contoso'
    CompanyName = 'Contoso'
    Copyright = 'Contoso. All rights reserved.'
    FunctionsToExport = @("Get-TargetResource", "Set-TargetResource", "Test-TargetResource")
}

参考

https://docs.microsoft.com/zh-cn/powershell/dsc/resources/resources

原文地址:https://www.cnblogs.com/talentzemin/p/11581528.html