gpt4 book ai didi

powershell - 在 DSC 中使用文件提供程序 - 确保目标仅包含来自源的文件

转载 作者:行者123 更新时间:2023-12-04 20:42:43 25 4
gpt4 key购买 nike

我创建了一个 DSC 资源来从某个来源复制一个 Modules 目录。我正在测试它以在我的环境中进行更广泛的部署。该资源在确保所有文件都在那里并且它们与源内容匹配方面做得很好,到目前为止一切都很好......

问题是这样的;我想确保目标或目标中是否有任何其他文件,它们会被删除。

这是我的代码:

Configuration TestRun
{
Param
(
$ComputerName = 'Localhost'
)
Node $ComputerName
{
File LoadModules
{
Ensure = 'Present'
Type = 'Directory'
Force = $true
Recurse = $true
SourcePath = "C:\git\Modules"
DestinationPath = 'C:\users\Jason\Documents\WindowsPowerShell\Modules'
Checksum = "SHA-256"
MatchSource = $true
}
}
}

在第一次运行配置后,我一直在目标目录中创建一个名为 Deleteme.flag 的文件来进行测试。到目前为止,我还没有任何运气让它真正被删除。

我尝试添加额外的文件提供程序要求以在目录运行之前删除它:
 File RemoveModules
{
Ensure = 'absent'
Type = 'Directory'
Force = $true
Recurse = $true
DestinationPath = 'C:\users\Jason\Documents\WindowsPowerShell\Modules'
}

不幸的是,这失败并出现以下错误:

The key properties combination 'C:\users\Jason\Documents\WindowsPowerShell\Modules' is duplicated for keys 'DestinationPath' of resource 'File' in node 'Localhost'. Please make sure key properties are unique for each resource in a node.



无论如何,我想用文件资源来做这件事,但显然,用脚本提供者或其他一些自定义资源来做这件事会很容易。提前感谢您的所有帮助!

最佳答案

我是 DSC 的新手。周日下午的大部分时间都在查看资源并试图弄清楚如何解决这个问题。所以,我真诚地感谢你。在 DSC 上查找很有趣。

我认为,这可以工作:

Configuration TestRun
{
Param
(
$ComputerName = 'Localhost'
)
Node $ComputerName
{
Script RemoveModules {
GetScript = {#needs to return hashtable.}
SetScript = {
$ump = "$HOME" + "\Documents\WindowsPowerShell\Modules\"
Remove-Item -Path $ump -Recurse -Force
}
TestScript = {
$ump = "$HOME" + "\Documents\WindowsPowerShell\Modules\"
$mp = "C:\git\Modules"
if((Compare-Object $(gci $mp) $(gci $ump))){
$false #at least one difference exists, SetScript will be called.
}else{
$true #nothing is different
}

}
}
File LoadModules
{
Ensure = 'Present'
Type = 'Directory'
Force = $true
Recurse = $true
SourcePath = "C:\git\Modules"
DestinationPath = 'C:\users\Jason\Documents\WindowsPowerShell\Modules'
DependsOn = "[Script]RemoveModules"
Checksum = "SHA-256"
MatchSource = $true
}
}
}

引用文献:
  • DSC Script Resource
  • DSC File Resource
  • PowerShellMagazine - Tag DSC
  • 关于powershell - 在 DSC 中使用文件提供程序 - 确保目标仅包含来自源的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23177212/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com