如何制作资源级变量

How to make resource level variables

例如,假设我有一个脚本资源:

configuration ChocolateyServer {
    node localhost {
        Script ChocolateyPackages {
            SetScript = {
                $tools = 'googlechrome,notepadplusplus,7zip,microsoftwse,octopusdeploy.tentacle,sqlserver-cmdlineutils'
                foreach($tool in $tools.Split(',')) {
                    if(($packages | ? { $_.ToString().ToLower().StartsWith($tool) }).Count -eq 0) {
                        choco install $tool -y
                    }
                }
            }
            TestScript = {
                $tools = 'googlechrome,notepadplusplus,7zip,microsoftwse,octopusdeploy.tentacle,sqlserver-cmdlineutils'
                $packages = (choco list -lr).ToLower()

                foreach($tool in $tools.Split(',')) {
                    if(($packages | ? { $_.ToString().ToLower().StartsWith($tool) }).Count -eq 0) {
                        return $false
                    }
                }

                return $true
            }
            GetScript = { return @{ Result = "nothing" } }
        }
    }
}

我想从这两个单独的函数中提取 $tools 以避免代码重复。我很高兴能够将 $tools 添加到我的脚本资源并在这两个函数之间共享它而无需定义它两次。

但是,尝试这样做会给我一个错误:

An attribute name for resource 'Script' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '$tools' with a simple string.

如何分享此代码?

脚本对象不允许定义任何额外的属性,但我能够在节点级别定义我的属性并在我的脚本资源中访问它们。

注意:必须使用 using 关键字引用这些变量,例如$using:tools

示例:

configuration ChocolateyServer {
    node localhost {
        #defining it here is ok
        $tools = 'googlechrome,notepadplusplus,7zip,microsoftwse,octopusdeploy.tentacle,sqlserver-cmdlineutils'

        Script ChocolateyPackages {
            #defining it here will cause an error

            SetScript = {
                foreach($tool in $using:tools.Split(',')) {
                    if(($packages | ? { $_.ToString().ToLower().StartsWith($tool) }).Count -eq 0) {
                        choco install $tool -y
                    }
                }
            }
            TestScript = {                  
                $packages = (choco list -lr).ToLower()

                foreach($tool in $using:tools.Split(',')) {
                    if(($packages | ? { $_.ToString().ToLower().StartsWith($tool) }).Count -eq 0) {
                        return $false
                    }
                }

                return $true
            }
            GetScript = { return @{ Result = "nothing" } }
        }
    }
}