【问题标题】:Using variables inside a DSC composite resource在 DSC 复合资源中使用变量
【发布时间】:2017-08-28 01:23:53
【问题描述】:

我对 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
    }
  }
}

执行此资源时,详细输出显示“正在测试”,并且由于 Path 参数为空,对 Test-Path 的调用失败。

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

我错过了什么?

【问题讨论】:

    标签: powershell powershell-dsc


    【解决方案1】:

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

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

    如果您需要使用配置脚本中的变量 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(脚本资源部分):

    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

    【讨论】:

    • 谢谢,这行得通。让复合资源变得如此丑陋,真是太可惜了。
    • 查看更新的答案。谢谢你的问题。终于有理由找到比丑陋的字符串替换更好的解决方案了:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多