about_DesiredStateConfiguration
应用到: Windows PowerShell 4.0
主题
about_Desired_State_Configuration
简短说明
提供 Windows PowerShell® 所需状态配置 (DSC) 功能的简介。
详细说明
DSC 是 Windows PowerShell 中的管理平台。它支持部署和管理软件服务的配置数据以及运行这些服务的环境。DSC 提供一组 Windows PowerShell 语言扩展、新的 cmdlet 和资源,可用于以声明方式指定你希望配置软件环境状态的方式。
Windows PowerShell 4.0 中引入了 DSC。
有关 DSC 的详细信息,请参阅 TechNet 库中的“Windows PowerShell 所需状态配置”,网址是 https://go.microsoft.com/fwlink/?LinkId=311940。
使用 DSC
若要使用 DSC 配置你的环境,请先使用 Configuration 关键字后跟标识符再后跟分隔该块的大括号对来定义 Windows PowerShell 脚本块。在配置块内,你可以定义节点块,这些节点块可为环境中的每个节点(计算机)指定所需的配置状态。节点块以 Node 关键字开头,后跟目标计算机的名称,该名称可以是一个变量。在计算机名称后是分隔节点块的大括号。在节点块中,你可以定义资源块来配置特定的资源。资源块以资源类型名称开头,后跟要为该块指定的标识符,再后跟分隔该块的大括号,如以下示例所示。
Configuration MyWebConfig
{
# Parameters are optional
param ($MachineName, $WebsiteFilePath)
# A Configuration block can have one or more Node blocks
Node $MachineName
{
# Next, specify one or more resource blocks
# WindowsFeature is one of the resources you can use in a Node block
# This example ensures the Web Server (IIS) role is installed
WindowsFeature IIS
{
# To ensure that the role is not installed, set Ensure to \"Absent\"
Ensure = "Present"
Name = "Web-Server" # Use the Name property from Get-WindowsFeature
}
# You can use the File resource to create files and folders
# \"WebDirectory\" is the name you want to use to refer to this instance
File WebDirectory
{
Ensure = "Present" # You can also set Ensure to "Absent“
Type = "Directory“ # Default is “File”
Recurse = $true
SourcePath = $WebsiteFilePath
DestinationPath = "C:\inetpub\wwwroot"
# Ensure that the IIS block is successfully run first before
# configuring this resource
Requires = "[WindowsFeature]IIS" # Use Requires for dependencies
}
}
}
若要创建配置,请使用调用 Windows PowerShell 函数的相同方法调用 Configuration 块,并传入你可能已定义的任何预期参数(上述示例中的两个参数)。例如,在此情况下:
MyWebConfig -MachineName "TestMachine" –WebsiteFilePath "\\filesrv\WebFiles" `
-OutputPath "C:\Windows\system32\temp" # OutputPath is optional
这将在你指定的路径中为每个节点生成 MOF 文件。这些 MOF 文件为每个节点指定所需的配置。接下来,使用以下 cmdlet 分析配置 MOF 文件、向每个节点发送其相应的配置并执行这些配置。
Start-DscConfiguration –Verbose -Wait -Path "C:\Windows\system32\temp"
使用 DSC 维护配置状态
使用 DSC 时,配置是幂等。这意味着如果你使用 DSC 执行相同的配置多次,则生成的配置状态将始终相同。因此,如果你怀疑环境中的任何节点可能偏离了所需的配置状态,则可以再次执行相同的 DSC 配置以将它们恢复到所需状态。你不需要修改配置脚本来仅处理其状态已偏离所需状态的资源。
以下示例显示如何验证给定节点上的实际配置状态是否已偏离在该节点上执行的最后一个 DSC 配置。在此示例中,我们将检查本地计算机的配置。
$session = New-CimSession -ComputerName "localhost"
Test-DscConfiguration -CimSession $session
内置 DSC 资源
DSC 提供了以下一组可在配置脚本中使用的内置资源:Registry、Script、Archive、File、WindowsFeature、Package、Environment、Group、User、Log、Service 和 WindowsProcess。上述示例演示如何使用 File 和 WindowsFeature 资源。若要查看可用于给定资源的所有属性,请将光标放在 Windows PowerShell ISE 中的配置脚本内的资源关键字(例如 File)上、按住 Ctrl,然后按空格键。
另请参阅
"Windows PowerShell 所需状态配置”