DSC 资源中是否可能有复杂的逻辑?
Is it possible to have complicated logic inside DSC Resource?
想知道在 DSC 资源中包含一些逻辑而无需编写自定义 DSC 资源的最佳方法是什么。示例如下。
我需要为内置 DSC 资源 File
提供 content
参数。我无法将 Function 放入 Configuration 中 return 该值,而且似乎也无法将逻辑放入 Content
标记中。对于这种情况,有什么可能的方法。
```
$filePath = Join-path -Path "$($env:programdata)" -ChildPath
"docker\config\daemon.json"
$filePath = Join-path -Path `"$($env:programdata)`" -ChildPath "docker\config\daemon.json`"
if (test-Path ($filePath))
{) { $jsonConfig = get-content $filePath | convertfrom-json
$jsonConfig.graph = $graphLocation
$jsonConfig | convertto-json
}
else { @{ graphLocation = "$graphLocation"} | convertto-json
}
```
如果您需要 运行 的逻辑作为 DSC 作业的一部分,那么您将需要求助于构建自定义 DSC 资源。请记住,所有 DSC 代码都会编译成 MOF 文件,而 MOF 文件不能 运行 任意 PowerShell 代码。因此内联函数在作业期间将不可用。
但是,您可以在编译阶段使用 运行 的逻辑。例如,计算将分配给 DSC 资源 属性 的 属性 值。
Configuration
最终只是一个以名称和脚本块作为参数的函数,在 PowerShell 中定义嵌套函数是有效的,尽管它必须在它之前的函数范围内定义正在使用。
Configuration MyConfig {
function ComplexLogic() {
"It works!"
}
Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
Node localhost {
Log Example {
Message = ComplexLogic
}
}
}
您还可以 运行 一个简单的 PowerShell 脚本来计算值,然后将这些值作为参数传递给 DSC 配置。
想知道在 DSC 资源中包含一些逻辑而无需编写自定义 DSC 资源的最佳方法是什么。示例如下。
我需要为内置 DSC 资源 File
提供 content
参数。我无法将 Function 放入 Configuration 中 return 该值,而且似乎也无法将逻辑放入 Content
标记中。对于这种情况,有什么可能的方法。
``` $filePath = Join-path -Path "$($env:programdata)" -ChildPath "docker\config\daemon.json"
$filePath = Join-path -Path `"$($env:programdata)`" -ChildPath "docker\config\daemon.json`"
if (test-Path ($filePath))
{) { $jsonConfig = get-content $filePath | convertfrom-json
$jsonConfig.graph = $graphLocation
$jsonConfig | convertto-json
}
else { @{ graphLocation = "$graphLocation"} | convertto-json
}
```
如果您需要 运行 的逻辑作为 DSC 作业的一部分,那么您将需要求助于构建自定义 DSC 资源。请记住,所有 DSC 代码都会编译成 MOF 文件,而 MOF 文件不能 运行 任意 PowerShell 代码。因此内联函数在作业期间将不可用。
但是,您可以在编译阶段使用 运行 的逻辑。例如,计算将分配给 DSC 资源 属性 的 属性 值。
Configuration
最终只是一个以名称和脚本块作为参数的函数,在 PowerShell 中定义嵌套函数是有效的,尽管它必须在它之前的函数范围内定义正在使用。
Configuration MyConfig {
function ComplexLogic() {
"It works!"
}
Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
Node localhost {
Log Example {
Message = ComplexLogic
}
}
}
您还可以 运行 一个简单的 PowerShell 脚本来计算值,然后将这些值作为参数传递给 DSC 配置。