在DSC复合资源中使用变量

时间:2017-04-03 08:49:00

标签: powershell powershell-dsc

我是PowerShell DSC的新手,对此的回答可能非常明显,但我找不到任何地方描述的类似问题。

我有一个PowerShell DSC复合资源,可以下载一些MSI并运行它们。下载文件的目录在几个地方被引用,所以我试图将它存储在一个变量中。但是,当我使用Start-DscConfiguration应用使用此资源的配置时,值始终显示为空。

以下是资源的示例:

Configuration xExample {

  Import-Module -ModuleName 'PSDesiredStateConfiguration'

  $path = 'C:\Temp\Installer.msi'

  Script Download {
    SetScript = { 
      Invoke-WebRequest -Uri "..." -OutFile $path 
    }
    GetScript = {
      @{ 
        Result = $(Test-Path $path)
      }
    }
    TestScript = {
      Write-Verbose "Testing $($path)"
      Test-Path $path
    }
  }
}

当执行此资源时,详细输出显示" Testing"由于Test-Path参数为空,对Path的调用失败。

我尝试在配置之外声明$path变量并使用$global无效。

我错过了什么?

1 个答案:

答案 0 :(得分:6)

DSC将脚本存储为已编译的mof文件中的字符串。标准变量不会扩展,因为它不知道要扩展哪些以及作为脚本的一部分保留哪些变量。

但是,您可以使用using - 范围来访问脚本之外的变量。在mof-compilation期间,定义变量的代码被添加到Test- / Set- / GetScript的每个scriptblock的开头。

  

如果您需要使用配置脚本中的变量   GetScript,TestScript或SetScript脚本块,使用$ using:   范围

来源:DSC Script Resources @ MSDN

示例:

Configuration xExample {

  Import-DscResource -ModuleName 'PSDesiredStateConfiguration'

  #Can also be set outside of Configuration-scriptblock
  $path = 'C:\Temp\Installer2.msi'

  Script Download {
    SetScript = { 
      Invoke-WebRequest -Uri "..." -OutFile $using:path
    }

    GetScript = {
      @{ 
        Result = $(Test-Path "$using:path")
      }
    }

    TestScript = {
      Write-Verbose "Testing $using:path"
      Test-Path "$using:path"
    }
  }
}

localhost.mof(scriptresource-part):

instance of MSFT_ScriptResource as $MSFT_ScriptResource1ref
{
ResourceID = "[Script]Download";
 GetScript = "$path ='C:\\Temp\\Installer2.msi'\n\n      @{ \n        Result = $(Test-Path \"$path\")\n      }\n    ";
 TestScript = "$path ='C:\\Temp\\Installer2.msi'\n\n      Write-Verbose \"Testing $path\"\n      Test-Path \"$path\"\n    ";
 SourceInfo = "::7::3::Script";
 SetScript = "$path ='C:\\Temp\\Installer2.msi'\n \n      Invoke-WebRequest -Uri \"...\" -OutFile $path\n    ";
 ModuleName = "PSDesiredStateConfiguration";

ModuleVersion = "1.0";

 ConfigurationName = "xExample";

};

来源:MSDN

相关问题