可以通过创建 PowerShell 类来定义 DSC 资源。 在基于类的 DSC 资源中,架构定义为类的属性,可以使用属性对其进行修改以指定属性类型。 资源是使用 Get、Set 和 Test 方法实现的, (与Get-TargetResource
Set-TargetResource
脚本资源) 中的 、 和 Test-TargetResource
函数相等。
在本文中,我们将创建一个名为 NewFile
的最小资源,用于管理指定路径中的文件。
有关 DSC 资源的详细信息,请参阅 DSC 资源。
注意
基于类的资源不支持泛型集合。
类资源的文件夹结构
若要使用 PowerShell 类实现 DSC 资源,请创建以下文件夹结构。 在 MyDscResource.psm1
中定义类,并且在 MyDscResource.psd1
中定义模块清单。
$env:ProgramFiles\WindowsPowerShell\Modules (folder)
|- MyDscResource (folder)
MyDscResource.psm1
MyDscResource.psd1
创建类
使用 class
关键字 (keyword) 创建 PowerShell 类。 若要指定类是 DSC 资源,请使用 DscResource()
属性。 类的名称是 DSC 资源的名称。
[DscResource()]
class NewFile {
}
声明属性
DSC 资源架构定义为 类的属性。 我们声明下列三个属性。
[DscProperty(Key)]
[string] $path
[DscProperty(Mandatory)]
[ensure] $ensure
[DscProperty()]
[string] $content
[DscProperty(NotConfigurable)]
[MyDscResourceReason[]] $Reasons
请注意,属性通过特性进行修改。 特性的含义如下:
- DscProperty(Key) :属性是必需的。 属性为键。 标记为键的所有属性的值必须组合在一起,以唯一标识配置中的资源实例。
- DscProperty(Mandatory) :属性是必需的。
- DscProperty(NotConfigurable) :属性为只读属性。 使用此属性标记的属性不能由配置设置,但由 Get 方法填充。
- DscProperty () :属性是可配置的,但不是必需的。
Path 和 SourcePath 属性都是字符串。 CreationTime 是 DateTime 属性。 Ensure 属性是一种枚举类型,定义如下。
enum Ensure {
Absent
Present
}
嵌入类
如果要包含一个具有可在 DSC 资源中使用的已定义属性的新类型,请创建一个具有属性类型的类,如前所述。
class MyDscResourceReason {
[DscProperty()]
[string] $Code
[DscProperty()]
[string] $Phrase
}
注意
类 MyDscResourceReason
在此处声明,并将模块的名称作为前缀。 虽然可以为嵌入类指定任何名称,但如果两个或多个模块定义同名的类并且都在配置中使用,则 PowerShell 将引发异常。
为了避免 DSC 中名称冲突导致的异常,请将嵌入类的名称作为模块名称的前缀。 如果嵌入类的名称已不太可能发生冲突,则可以在不使用前缀的情况下使用它。
如果 DSC 资源旨在与 Azure Automanage 的计算机配置功能一起使用,请始终为为 Reasons 属性创建的嵌入式类的名称添加前缀。
公共和专用函数
可以在同一模块文件中创建 PowerShell 函数,并在 DSC 资源类的方法中使用这些函数。 必须在模块清单的 FunctionsToExport 设置中将函数导出为模块成员。 这些函数中的脚本块可能会调用未导出的函数。
<#
Public Functions
#>
function Get-File {
param(
[ensure]$ensure,
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$path,
[String]$content
)
$fileContent = [MyDscResourceReason]::new()
$fileContent.code = 'file:file:content'
$filePresent = [MyDscResourceReason]::new()
$filePresent.code = 'file:file:path'
$ensureReturn = 'Absent'
$fileExists = Test-Path -Path $path -ErrorAction SilentlyContinue
if ($fileExists) {
$filePresent.phrase = @(
"The file was expected to be: $ensure"
"The file exists at path: $path"
) -join "`n"
$existingFileContent = Get-Content $path -Raw
if ([string]::IsNullOrEmpty($existingFileContent)) {
$existingFileContent = ''
}
if (![string]::IsNullOrEmpty($content)) {
$content = $content | ConvertTo-SpecialChars
}
$fileContent.phrase = @(
"The file was expected to contain: $content"
"The file contained: $existingFileContent"
) -join "`n"
if ($content -eq $existingFileContent) {
$ensureReturn = 'Present'
}
} else {
$filePresent.phrase = @(
"The file was expected to be: $ensure"
"The file does not exist at path: $path"
) -join "`n"
$path = 'file not found'
}
@{
Ensure = $ensureReturn
Path = $path
Content = $existingFileContent
Reasons = @($filePresent,$fileContent)
}
}
function Set-File {
param(
[ensure]$ensure = "Present",
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$path,
[String]$content
)
Remove-Item $path -Force -ErrorAction SilentlyContinue
if ($ensure -eq "Present") {
New-Item $path -ItemType File -Force
if ([ValidateNotNullOrEmpty()]$content) {
$content | ConvertTo-SpecialChars | Set-Content $path -NoNewline -Force
}
}
}
function Test-File {
param(
[ensure]$ensure = "Present",
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$path,
[String]$content
)
$test = $false
$get = Get-File @PSBoundParameters
if ($get.ensure -eq $ensure) {
$test = $true
}
$test
}
<#
Private Functions
#>
function ConvertTo-SpecialChars {
param(
[parameter(Mandatory = $true,ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[string]$string
)
$specialChars = @{
'`n' = "`n"
'\\n' = "`n"
'`r' = "`r"
'\\r' = "`r"
'`t' = "`t"
'\\t' = "`t"
}
foreach ($char in $specialChars.Keys) {
$string = $string -replace ($char,$specialChars[$char])
}
$string
}
实现该方法
Get、Set 和 Test 方法类似于Get-TargetResource
脚本资源中的 、 Set-TargetResource
和 Test-TargetResource
函数。
最佳做法是限制类实现中的代码量。 将大部分代码移动到导出的模块函数中,可以独立测试这些函数。
<#
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.
#>
[NewFile] Get() {
$get = Get-File -ensure $this.ensure -path $this.path -content $this.content
return $get
}
<#
This method is equivalent of the Set-TargetResource script function.
It sets the Resource to the desired state.
#>
[void] Set() {
$set = Set-File -ensure $this.ensure -path $this.path -content $this.content
}
<#
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() {
$test = Test-File -ensure $this.ensure -path $this.path -content $this.content
return $test
}
完整文件
完整类文件如下。
enum ensure {
Absent
Present
}
<#
This class is used within the DSC Resource to standardize how data
is returned about the compliance details of the machine. Note that
the class name is prefixed with the module name - this helps prevent
errors raised when multiple modules with DSC Resources define the
Reasons property for reporting when they're out-of-state.
#>
class MyDscResourceReason {
[DscProperty()]
[string] $Code
[DscProperty()]
[string] $Phrase
}
<#
Public Functions
#>
function Get-File {
param(
[ensure]$ensure,
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$path,
[String]$content
)
$fileContent = [MyDscResourceReason]::new()
$fileContent.code = 'file:file:content'
$filePresent = [MyDscResourceReason]::new()
$filePresent.code = 'file:file:path'
$ensureReturn = 'Absent'
$fileExists = Test-Path -Path $path -ErrorAction SilentlyContinue
if ($fileExists) {
$filePresent.phrase = @(
"The file was expected to be: $ensure"
"The file exists at path: $path"
) -join "`n"
$existingFileContent = Get-Content $path -Raw
if ([string]::IsNullOrEmpty($existingFileContent)) {
$existingFileContent = ''
}
if (![string]::IsNullOrEmpty($content)) {
$content = $content | ConvertTo-SpecialChars
}
$fileContent.phrase = @(
"The file was expected to contain: $content"
"The file contained: $existingFileContent"
) -join "`n"
if ($content -eq $existingFileContent) {
$ensureReturn = 'Present'
}
} else {
$filePresent.phrase = @(
"The file was expected to be: $ensure"
"The file does not exist at path: $path"
) -join "`n"
$path = 'file not found'
}
@{
ensure = $ensureReturn
path = $path
content = $existingFileContent
Reasons = @($filePresent,$fileContent)
}
}
function Set-File {
param(
[ensure]$ensure = "Present",
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$path,
[String]$content
)
Remove-Item $path -Force -ErrorAction SilentlyContinue
if ($ensure -eq "Present") {
New-Item $path -ItemType File -Force
if ([ValidateNotNullOrEmpty()]$content) {
$content | ConvertTo-SpecialChars | Set-Content $path -NoNewline -Force
}
}
}
function Test-File {
param(
[ensure]$ensure = "Present",
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$path,
[String]$content
)
$test = $false
$get = Get-File @PSBoundParameters
if ($get.ensure -eq $ensure) {
$test = $true
}
return $test
}
<#
Private Functions
#>
function ConvertTo-SpecialChars {
param(
[parameter(Mandatory = $true,ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[string]$string
)
$specialChars = @{
'`n' = "`n"
'\\n' = "`n"
'`r' = "`r"
'\\r' = "`r"
'`t' = "`t"
'\\t' = "`t"
}
foreach ($char in $specialChars.Keys) {
$string = $string -replace ($char,$specialChars[$char])
}
return $string
}
<#
This Resource manages the file in a specific path.
[DscResource()] indicates the class is a DSC Resource
#>
[DscResource()]
class NewFile {
<#
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 is optional. When provided, the content of the file
will be overwridden by this value.
#>
[DscProperty()]
[string] $content
<#
This property reports the reasons the machine is or is not compliant.
[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)]
[MyDscResourceReason[]] $Reasons
<#
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.
#>
[NewFile] Get() {
$get = Get-File -ensure $this.ensure -path $this.path -content $this.content
return $get
}
<#
This method is equivalent of the Set-TargetResource script function.
It sets the Resource to the desired state.
#>
[void] Set() {
$set = Set-File -ensure $this.ensure -path $this.path -content $this.content
}
<#
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() {
$test = Test-File -ensure $this.ensure -path $this.path -content $this.content
return $test
}
}
创建清单
若要使基于类的 DSC 资源可用,必须在清单文件中包括一个 DscResourcesToExport
语句,用于指示模块导出 DSC 资源。 我们的清单如下所示:
@{
# Script module or binary module file associated with this manifest.
RootModule = 'NewFile.psm1'
# Version number of this module.
ModuleVersion = '1.0.0'
# ID used to uniquely identify this module
GUID = 'fad0d04e-65d9-4e87-aa17-39de1d008ee4'
# Author of this module
Author = 'Microsoft Corporation'
# Company or vendor of this module
CompanyName = 'Microsoft Corporation'
# Copyright statement for this module
Copyright = ''
# Description of the functionality provided by this module
Description = 'Create and set content of a file'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '5.0'
# Functions to export from this module
FunctionsToExport = @('Get-File','Set-File','Test-File')
# DSC Resources to export from this module
DscResourcesToExport = @('NewFile')
# 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 = @(Power Plan, Energy, Battery)
# 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
}
}
测试资源
在前面所述的文件夹结构中保存类和清单文件后,可以创建使用新 DSC 资源的 DSC 配置。 下面 Configuration
检查是否存在 文件 /tmp/test.txt
,以及内容是否与 Content 属性提供的字符串匹配。 如果不,则写入整个文件。
Configuration MyConfig {
Import-DSCResource -ModuleName NewFile
NewFile testFile {
Path = "/tmp/test.txt"
Content = "DSC Rocks!"
Ensure = "Present"
}
}
MyConfig
在模块中声明多个基于类的 DSC 资源
一个模块可以定义多个基于类的 DSC 资源。 需要在同一 .psm1
文件中声明所有类,并在清单中包含 .psd1
每个名称。
$env:ProgramFiles\PowerShell\Modules (folder)
|- MyDscResource (folder)
|- MyDscResource.psm1
MyDscResource.psd1