使用 C# 撰寫 DSC 資源
適用於:Windows PowerShell 4.0、Windows PowerShell 5.0
一般而言,Windows PowerShell 預期狀態設定 (DSC) 自訂資源是在 PowerShell 指令碼中實作。 但您也可以用 C# 撰寫 Cmdlet 來實作 DSC 自訂資源的功能。 如需以 C# 撰寫 Cmdlet 的簡介,請參閱撰寫 Windows PowerShell Cmdlet。
除了用 C# 將資源當做 Cmdlet 實作,建立 MOF 結構描述、建立資料夾結構、匯入和使用自訂之 DSC 資源的程序,一如撰寫自訂的 DSC 資源與 MOF 中所述。
撰寫 Cmdlet 式的資源
本例中,我們會實作簡單的資源,管理文字檔案及其內容。
撰寫 MOF 結構描述
以下是 MOF 資源定義。
[ClassVersion("1.0.0"), FriendlyName("xDemoFile")]
class MSFT_XDemoFile : OMI_BaseResource
{
[Key, Description("path")] String Path;
[Write, Description("Should the file be present"), ValueMap{"Present","Absent"}, Values{"Present","Absent"}] String Ensure;
[Write, Description("Contentof file.")] String Content;
};
設定 Visual Studio 專案
設定 Cmdlet 專案
- 開啟 Visual Studio。
- 建立 C# 專案並提供名稱。
- 從可用的專案範本中選取 [類別庫] 。
- 按一下 [確定] 。
- 在專案中加入 System.Automation.Management.dll 的組件參考。
- 變更組件名稱使符合資源名稱。 如此,組件應命名為 MSFT_XDemoFile。
撰寫 Cmdlet 程式碼
下列 C# 程式碼實作 Get-TargetResource
、Set-TargetResource
和 Test-TargetResource
Cmdlet。
namespace cSharpDSCResourceExample
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation; // Windows PowerShell assembly.
#region Get-TargetResource
[OutputType(typeof(System.Collections.Hashtable))]
[Cmdlet(VerbsCommon.Get, "TargetResource")]
public class GetTargetResource : PSCmdlet
{
[Parameter(Mandatory = true)]
public string Path { get; set; }
/// <summary>
/// Implement the logic to return the current state of the resource as a hashtable with
/// keys being the resource properties and the values are the corresponding current
/// value on the machine.
/// </summary>
protected override void ProcessRecord()
{
var currentResourceState = new Dictionary<string, string>();
if (File.Exists(Path))
{
currentResourceState.Add("Ensure", "Present");
// read current content
string CurrentContent = "";
using (var reader = new StreamReader(Path))
{
CurrentContent = reader.ReadToEnd();
}
currentResourceState.Add("Content", CurrentContent);
}
else
{
currentResourceState.Add("Ensure", "Absent");
currentResourceState.Add("Content", "");
}
// write the hashtable in the PS console.
WriteObject(currentResourceState);
}
}
# endregion
#region Set-TargetResource
[OutputType(typeof(void))]
[Cmdlet(VerbsCommon.Set, "TargetResource")]
public class SetTargetResource : PSCmdlet
{
[Parameter(Mandatory = true)]
public string Path { get; set; }
[Parameter(Mandatory = false)]
[ValidateSet("Present", "Absent", IgnoreCase = true)]
public string Ensure {
get
{
// set the default to present.
return (this._ensure ?? "Present") ;
}
set
{
this._ensure = value;
}
}
[Parameter(Mandatory = false)]
public string Content {
get { return (string.IsNullOrEmpty(this._content) ? "" : this._content); }
set { this._content = value; }
}
private string _ensure;
private string _content;
/// <summary>
/// Implement the logic to set the state of the machine to the desired state.
/// </summary>
protected override void ProcessRecord()
{
WriteVerbose(string.Format("Running set with parameters {0}{1}{2}", Path, Ensure, Content));
if (File.Exists(Path))
{
if (Ensure.Equals("absent", StringComparison.InvariantCultureIgnoreCase))
{
File.Delete(Path);
}
else
{
// file already exist and ensure "present" is specified. start writing the content to a file
if (!string.IsNullOrEmpty(Content))
{
string existingContent = null;
using (var reader = new StreamReader(Path))
{
existingContent = reader.ReadToEnd();
}
// check if the content of the file mathes the content passed
if (!existingContent.Equals(Content, StringComparison.InvariantCultureIgnoreCase))
{
WriteVerbose("Existing content did not match with desired content updating the content of the file");
using (var writer = new StreamWriter(Path))
{
writer.Write(Content);
writer.Flush();
}
}
}
}
}
else
{
if (Ensure.Equals("present", StringComparison.InvariantCultureIgnoreCase))
{
// if nothing is passed for content just write "" otherwise write the content passed.
using (var writer = new StreamWriter(Path))
{
WriteVerbose(string.Format("Creating a file under path {0} with content {1}", Path, Content));
writer.Write(Content);
}
}
}
/* if you need to reboot the VM. please add the following two line of code.
PSVariable DscMachineStatus = new PSVariable("DSCMachineStatus", 1, ScopedItemOptions.AllScope);
this.SessionState.PSVariable.Set(DscMachineStatus);
*/
}
}
# endregion
#region Test-TargetResource
[Cmdlet("Test", "TargetResource")]
[OutputType(typeof(Boolean))]
public class TestTargetResource : PSCmdlet
{
[Parameter(Mandatory = true)]
public string Path { get; set; }
[Parameter(Mandatory = false)]
[ValidateSet("Present", "Absent", IgnoreCase = true)]
public string Ensure
{
get
{
// set the default to present.
return (this._ensure ?? "Present");
}
set
{
this._ensure = value;
}
}
[Parameter(Mandatory = false)]
public string Content
{
get { return (string.IsNullOrEmpty(this._content) ? "" : this._content); }
set { this._content = value; }
}
private string _ensure;
private string _content;
/// <summary>
/// Return a boolean value which indicates wheather the current machine is in desired state or not.
/// </summary>
protected override void ProcessRecord()
{
if (File.Exists(Path))
{
if( Ensure.Equals("absent", StringComparison.InvariantCultureIgnoreCase))
{
WriteObject(false);
}
else
{
// check if the content matches
string existingContent = null;
using (var stream = new StreamReader(Path))
{
existingContent = stream.ReadToEnd();
}
WriteObject(Content.Equals(existingContent, StringComparison.InvariantCultureIgnoreCase));
}
}
else
{
WriteObject(Ensure.Equals("Absent", StringComparison.InvariantCultureIgnoreCase));
}
}
}
# endregion
}
部署資源
已編譯的 DLL 檔案應該儲存在類似於指令碼式資源的檔案結構中。 以下是這項資源的資料夾結構。
$env: psmodulepath (folder)
|- MyDscResources (folder)
|- MyDscResources.psd1 (file, required)
|- DSCResources (folder)
|- MSFT_XDemoFile (folder)
|- MSFT_XDemoFile.psd1 (file, optional)
|- MSFT_XDemoFile.dll (file, required)
|- MSFT_XDemoFile.schema.mof (file, required)