我可以在DSC文件资源中使用动态变量吗?

时间:2015-04-15 01:33:11

标签: powershell runtime dsc

如何获取所需状态配置的文件资源以在运行时确定它的$ DestinationPath? 这似乎仅在生成mof文件时设置。

我的下面的脚本显示了我想要做的事情。我知道为什么它不起作用,我无法找到如何使它发挥作用。

该脚本查看目标计算机上的PSModulePath变量,并从变量中提取单个路径。我想将此路径传递给脚本中的文件资源,以在该路径中安装一些自定义Powershell模块。

我使用变量$ LocalInstallPath,但这不起作用,因为它是在创建mof文件时在文件资源中设置的。尝试将设置作为环境变量,但同样的问题。

有办法做到这一点吗?

Configuration InstallCustomPowershellModules
{
    param($MachineName)

    Node $MachineName
    {
        $CustomModuleSource = '\\fileserver\modules\Module1'

        Script GetLocalPath
        {
            SetScript = { 
                $FullPath = [Environment]::GetEnvironmentVariable("PSModulePath", "Machine")
                $SplitPath = $FullPath -split ";"
                foreach ($ShortPath in $SplitPath)
                {
                    $result = Select-String -Pattern 'system32' -InputObject $ShortPath
                    if($result -ne $null)
                    {
                        break
                    }
                }
                $LocalInstallPath = $ShortPath
            }

            TestScript = { $false }
            GetScript  = { $true }         
        }


       File InstallCustomModule
        {
           Ensure = 'Present'
           Type = 'Directory'
           SourcePath = $CustomModuleSource
           DestinationPath = $LocalInstallPath
           Force = $true
           Recurse = $true
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我们(尚未)在运行时支持扩展环境变量。因此,您唯一的选择是使用脚本资源进行复制

答案 1 :(得分:0)

如果没有单独的脚本块

,则可以获得$LocalInstallPath
$LocalInstallPath = $env:PSModulePath.Split(';')|?{$_ -like '*system32*'} | select -First 1

所以

File InstallCustomModule
        {
           Ensure = 'Present'
           Type = 'Directory'
           SourcePath = $CustomModuleSource
           DestinationPath = $env:PSModulePath.Split(';')|?{$_ -like '*system32*'} | select -First 1
           Force = $true
           Recurse = $true
        }

P.S。我没有在你的场景中测试这段代码,希望这会有用。