適用於:Windows PowerShell 4.0、Windows PowerShell 5.0
本練習會逐步解說從頭到尾建立和套用所需狀態組態 (DSC) 組態。 在下列範例中,您將學習如何撰寫和套用非常簡單的組態。 配置將確保您的本機電腦上存在“HelloWorld.txt”文件。 如果您刪除檔案,DSC 會在下次更新時重新建立檔案。
如需 DSC 是什麼及其運作方式的概觀,請參閱 開發人員所需的狀態設定概觀。
需求
若要執行此範例,您需要執行 PowerShell 4.0 或更新版本的電腦。
撰寫組態
DSC 設定 是一項特殊的 PowerShell 函式,可定義您要如何設定一或多部目標電腦 (節點) 。
在 PowerShell ISE 或其他 PowerShell 編輯器中,輸入下列內容:
Configuration HelloWorld {
# Import the module that contains the File resource.
Import-DscResource -ModuleName PsDesiredStateConfiguration
# The Node statement specifies which targets to compile MOF files for, when
# this configuration is executed.
Node 'localhost' {
# The File resource can ensure the state of files, or copy them from a
# source to a destination with persistent updates.
File HelloWorld {
DestinationPath = "C:\Temp\HelloWorld.txt"
Ensure = "Present"
Contents = "Hello World from DSC!"
}
}
}
這很重要
在需要匯入多個模組的更進階案例中,以便您可以在相同的組態中使用許多 DSC 資源,請務必使用 Import-DscResource將每個模組放在單獨的行中。 這更容易在原始檔控制中維護,而且在 Azure 狀態設定中使用 DSC 時需要。
Configuration HelloWorld {
# Import the module that contains the File resource.
Import-DscResource -ModuleName PsDesiredStateConfiguration
Import-DscResource -ModuleName xWebAdministration
將檔案儲存為「HelloWorld.ps1」。
定義配置就像定義函數一樣。
Node 區塊指定要配置的目標節點,在此案例localhost中為 。
組態會呼叫一個 資源,即 File 資源。 資源會執行確保目標節點處於組態所定義的狀態的工作。
編譯組態
若要將 DSC 設定套用至節點,必須先將其編譯成 MOF 檔案。 執行配置(就像函數一樣)將為區塊定義的Node每個節點編譯一個.mof檔案。 若要執行組態,您需要將指令碼點源HelloWorld.ps1到目前範圍。 如需詳細資訊,請參閱 about_Scripts。
點源您的HelloWorld.ps1腳本,方法是在您存儲腳本的路徑中鍵入(點,空格)之後. 。 然後,您可以像函數一樣呼叫配置來執行您的配置。 您也可以叫用腳本底部的組態函式,這樣就不需要點源了。
. C:\Scripts\HelloWorld.ps1
HelloWorld
這會產生下列輸出:
Directory: C:\Scripts\HelloWorld
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 3/13/2017 5:20 PM 2746 localhost.mof
套用組態
現在您已經有了編譯的 MOF,您可以呼叫 Start-DscConfiguration Cmdlet,將設定套用至目標節點 (在此案例中為本機電腦) 。
Cmdlet Start-DscConfiguration 會告知 本機組態管理員 (LCM) (DSC 的引擎) 套用組態。 LCM 會執行呼叫 DSC 資源以套用組態的工作。
使用下列程式碼來執行 Start-DSCConfiguration Cmdlet。 指定儲存 ur localhost.mof 的目錄路徑至 Path 參數。
Start-DSCConfiguration Cmdlet 會查看為任何<computername>.mof檔案指定的目錄。
Start-DSCConfiguration Cmdlet 會嘗試將它找到的每個.mof檔案套用至檔案名稱所指定的檔案 computername (“localhost”、“server01”、“dc-02” 等)。
備註
如果未指定參數 -Wait , Start-DSCConfiguration 則會建立背景工作來執行作業。 指定參數可讓您 -Verbose 監視作業的 詳細 輸出。
-Wait,兩者 -Verbose 都是選用參數。
Start-DscConfiguration -Path C:\Scripts\HelloWorld -Verbose -Wait
測試組態
Start-DSCConfiguration Cmdlet 完成後,您應該會在您指定的位置看到一個HelloWorld.txt檔案。 您可以使用 Get-Content Cmdlet 來驗證內容。
您也可以使用 Test-DSCConfiguration 來測試目前的狀態。
如果節點目前符合套用的組態,則應該會輸出 True 。
Test-DSCConfiguration
True
Get-Content -Path C:\Temp\HelloWorld.txt
Hello World from DSC!
重新套用組態
若要再次套用您的設定,您可以移除「設定」所建立的文字檔。 將 cmdlet 與 Start-DSCConfiguration 參數搭配使用 -UseExisting 。 此 -UseExisting 參數會 Start-DSCConfiguration 指示重新套用「current.mof」檔案,該檔案代表最近成功套用的組態。
Remove-Item -Path C:\Temp\HelloWorld.txt
後續步驟
- 如需有關 DSC 組態的更多資訊,請參閱 DSC 組態。
- 查看可用的 DSC 資源,以及如何在 DSC 資源中建立自訂 DSC 資源。
- 在 PowerShell 資源庫中尋找 DSC 設定和資源。