適用於:Windows PowerShell 5.0
在 Windows PowerShell 5.0 中引進 PowerShell 類別之後,您現在可以藉由建立類別來定義 DSC 資源。 類別會同時定義資源的架構和實作,因此不需要建立個別的MOF檔案。 類別型資源的資料夾結構也更簡單,因為不需要 DSCResources 資料夾。
在以類別為基礎的 DSC 資源中,架構會定義為類別的屬性,該屬性可以使用屬性來修改,以指定屬性類型。 資源是由 、 Set()和方法實Get()作 (Get-TargetResource相當於腳本資源中的 、 Set-TargetResource和Test-TargetResource函Test()式。
在本文中,我們將建立一個名為 NewFile 的簡單資源,用於管理指定路徑中的檔案。
如需 DSC 資源的詳細資訊,請參閱 建置自訂 Windows PowerShell 所需狀態設定資源
注意
類別型資源不支援泛型集合。
類別資源的資料夾結構
若要使用PowerShell類別實作 DSC 自訂資源,請建立下列資料夾結構。
類別定義在 中MyDscResource.psm1,模組資訊清單定義在 中。MyDscResource.psd1
$env:ProgramFiles\WindowsPowerShell\Modules (folder)
|- MyDscResource (folder)
MyDscResource.psm1
MyDscResource.psd1
建立類別
您可以使用 類別關鍵詞來建立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(必要):屬性是必要的。
-
DscProperty(NotConfigurable):屬性是唯讀的。 標示有此屬性的內容無法由組態設定,但會在存在時由
Get()方法填入。 - DscProperty():屬性是可設定的,但不是必需的。
和$Path$SourcePath屬性都是字串。 是 DateTime$CreationTime 屬性。 屬性 $Ensure 是列舉類型,定義如下。
enum Ensure
{
Absent
Present
}
內嵌類別
如果您想要包含可在資源內使用之已定義屬性的新類型,只要建立具有屬性類型的類別,如上所述。
class MyDscResourceReason {
[DscProperty()]
[string] $Code
[DscProperty()]
[string] $Phrase
}
注意
MyDscResourceReason該類別在此處以模組名稱作為前綴來宣告。 雖然您可以為內嵌類別提供任何名稱,但如果兩個或多個模組定義具有相同名稱的類別,而且兩者都用於組態,則 PowerShell 會引發例外狀況。
若要避免 DSC 中名稱衝突所造成的例外狀況,請在內嵌類別的名稱前面加上模組名稱。 如果內嵌類別的名稱已經不太可能發生衝突,您可以使用它而不使用前置詞。
如果您的 DSC 資源是設計用於 Azure 機器設定,請務必在前置您為 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 -ErrorAction SilentlyContinue
if ($true -eq $fileExists) {
$filePresent.phrase = "The file was expected to be: $ensure`nThe file exists at path: $path"
$existingFileContent = Get-Content $path -Raw
if ([string]::IsNullOrEmpty($existingFileContent)) {
$existingFileContent = ''
}
if ($false -eq ([string]::IsNullOrEmpty($content))) {
$content = $content | ConvertTo-SpecialChars
}
$fileContent.phrase = "The file was expected to contain: $content`nThe file contained: $existingFileContent"
if ($content -eq $existingFileContent) {
$ensureReturn = 'Present'
}
}
else {
$filePresent.phrase = "The file was expected to be: $ensure`nThe file does not exist at path: $path"
$path = 'file not found'
}
return @{
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
}
實作方法
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 -ErrorAction SilentlyContinue
if ($true -eq $fileExists) {
$filePresent.phrase = "The file was expected to be: $ensure`nThe file exists at path: $path"
$existingFileContent = Get-Content $path -Raw
if ([string]::IsNullOrEmpty($existingFileContent)) {
$existingFileContent = ''
}
if ($false -eq ([string]::IsNullOrEmpty($content))) {
$content = $content | ConvertTo-SpecialChars
}
$fileContent.phrase = "The file was expected to contain: $content`nThe file contained: $existingFileContent"
if ($content -eq $existingFileContent) {
$ensureReturn = 'Present'
}
}
else {
$filePresent.phrase = "The file was expected to be: $ensure`nThe file does not exist at path: $path"
$path = 'file not found'
}
return @{
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 式,以指示模組匯出資源。 我們的指令清單看起來像這樣:
@{
# 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 組態的相關資訊,請參閱 制定組態。 下列設定會檢查檔案 at /tmp/test.txt 是否存在,以及內容是否符合屬性 'Content' 所提供的字串。 如果沒有,則會寫入整個檔案。
Configuration MyConfig
{
Import-DSCResource -ModuleName NewFile
NewFile testFile
{
Path = "/tmp/test.txt"
Content = "DSC Rocks!"
Ensure = "Present"
}
}
MyConfig
支援 PsDscRunAsCredential
[筆記]PowerShell 5.0 和更新版本支援 PsDscRunAsCredential 。
PsDscRunAsCredential 屬性可用於 DSC 設定資源區塊,以指定資源應該在一組指定的認證下執行。 如需詳細資訊,請參閱 使用使用者認證執行 DSC。
需要或不允許資源的 PsDscRunAsCredential
此 DscResource() 屬性會採用選擇性參數 RunAsCredential。 此參數接受三個值的其中一個:
-
OptionalPsDscRunAsCredential 對於呼叫此資源的組態是選擇性的。 這是預設值。 -
MandatoryPsDscRunAsCredential 必須用於呼叫此資源的任何設定。 -
NotSupported呼叫此資源的組態無法使用 PsDscRunAsCredential。 -
Default與Optional相同。
例如,使用下列屬性來指定您的自訂資源不支援使用 PsDscRunAsCredential:
[DscResource(RunAsCredential=NotSupported)]
class NewFile {
}
在模組中宣告多個類別資源
模組可以定義多個類別型 DSC 資源。 您只需在同一個檔案中 .psm1 宣告所有類別,並在資訊清單中 .psd1 包含每個名稱即可。
$env:ProgramFiles\WindowsPowerShell\Modules (folder)
|- MyDscResource (folder)
|- MyDscResource.psm1
MyDscResource.psd1
存取用戶內容
若要從自訂資源內存取使用者內容,您可以使用自動變數 $global:PsDscContext。
例如,下列程式代碼會撰寫資源執行至詳細資訊輸出數據流的用戶內容:
if (PsDscContext.RunAsUser) {
Write-Verbose "User: $global:PsDscContext.RunAsUser";
}