如何围绕文件资源创建PowerShell DSC foreach循环,以复制配置中定义的多个文件?

Mar*_*ber 6 powershell dsc

我正在尝试使用PowerShell DSC执行多个文件副本.我的配置有一个需要复制的源/目标文件列表.但是,File资源需要具有唯一的名称,以便您可以对资源执行依赖项.

我是PowerShell的新手,我正在尝试找出DSC脚本(.ps1)的正确格式,以允许围绕File资源进行foreach.目前,我的代码给了我一个"重复资源标识符"错误,因为看起来文件资源没有获得唯一的名称.

配置(psd1文件):

{
AllNodes = @(
@{
  NodeName = '*'
  BuildOutputRoot = 'C:\_BuildDrop\'
  FilesToCopy = @(
    @{
      SourcePath = 'C:\_BuildDrop\SampleConfig.xml'
      TargetPath = 'C:\SampleCode\SampleConfig.xml'
    },
    @{
      SourcePath = 'C:\_BuildDrop\SampleConfig2.xml'
      TargetPath = 'C:\SampleCode\SampleConfig2.xml'
    },
Run Code Online (Sandbox Code Playgroud)

用于DSC(代码段)的Powershell ps1文件:

Configuration MachineToolsFilesAndDirectories
{
# Copy files on all machines
Node $AllNodes.NodeName
{
    foreach ($FileToCopy in $Node.FilesToCopy)
    {
        File $FileToCopy$Number
        {
            Ensure = "Present"
            Type = "File"
            Recurse = $false
            SourcePath = $FileToCopy.SourcePath
            DestinationPath = $FileToCopy.TargetPath
        }
    }
Run Code Online (Sandbox Code Playgroud)

bri*_*ist 5

看起来您永远不会定义或更改值,$Number因此每个File资源最终都使用相同的名称.尝试这样的事情.

Configuration MachineToolsFilesAndDirectories
{
# Copy files on all machines
Node $AllNodes.NodeName
{
    $Number = 0
    foreach ($FileToCopy in $Node.FilesToCopy)
    {
        $Number += 1
        $thisFile = "$FileToCopy$Number"

        File $thisFile
        {
            Ensure = "Present"
            Type = "File"
            Recurse = $false
            SourcePath = $FileToCopy.SourcePath
            DestinationPath = $FileToCopy.TargetPath
        }
    }
}
Run Code Online (Sandbox Code Playgroud)