适用于: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 将配置应用于目标节点 (在本例中为本地计算机) 。
该 Start-DscConfiguration cmdlet 告知 本地配置管理器 (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
测试配置
cmdlet 完成后 Start-DSCConfiguration ,应会在指定位置看到一个 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 配置和资源。