所需状态配置 无法从脚本资源获取块获取哈希表


我已经使用 1.1

中的内置脚本资源以及 xScript 5.1.0.0 对此进行了测试,并得到了相同的结果。我的设置和测试块工作正常。我正在使用其他几个非常相似的脚本资源,它们对于 get 块也可以正常工作。

我已经尝试了很多语法变化,但它总是是一样的。我知道块正在运行,因为我注释掉了删除创建的文件并看到文件的行。我还在 powershell 中将其作为函数运行,并将输出通过管道传输到 Get-Member,可以看到它确实是一个返回的 hastable。

附带说明一下,我真的不喜欢我在这里使用的通过 DSC 管理此设置的方法。只要它仍在 DSC 中,我就对其他想法持开放态度。

Script StorePasswordsUsingReversibleEncyption
{
    SetScript   = {
        secedit /export /cfg c:tempsecpol.cfg
        (gc C:tempsecpol.cfg).replace("ClearTextPassword = 1", "ClearTextPassword = 0") | Out-File C:tempsecpol.cfg
        secedit /configure /db c:windowssecuritylocal.sdb /cfg c:tempsecpol.cfg /areas SECURITYPOLICY /quiet
        rm -force c:tempsecpol.cfg -confirm:$false
    } 
    TestScript = {
        secedit /export /cfg c:tempsecpol.cfg
        $str = (Get-Content 'c:tempsecpol.cfg' | select-String 'ClearTextPassword' -SimpleMatch).ToString()
        rm -force c:tempsecpol.cfg -confirm:$false
        if ($str -eq 'ClearTextPassword = 0') {return $true}
        else {return $false}            
    } 
    # Not working yet           
    GetScript   = {
        secedit /export /cfg c:tempsecpol.cfg
        $str = (Get-Content 'c:tempsecpol.cfg' | select-String 'ClearTextPassword' -SimpleMatch).ToString()
        rm -force c:tempsecpol.cfg -confirm:$false
        return @{Result = $str}     
    }    
}

运行 Get-DSCConfiguration 后,控制台中返回的输出如下所示:

Get-DscConfiguration : PowerShell DSC resource MSFT_ScriptResource  failed to execute Get-TargetResource functionality 
with error message: Failure to get the results from the script in a hash table format. 
At line:1 char:1
+ Get-DscConfiguration
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (MSFT_DSCLocalConfigurationManager:root/Microsoft/...gurationManager)  
   [Get-DscConfiguration], CimException
    + FullyQualifiedErrorId : ProviderOperationExecutionFailure,Get-DscConfiguration

试试这个:

 GetScript   = {
        $null = secedit /export /cfg c:tempsecpol.cfg
        $str = (Get-Content 'c:tempsecpol.cfg' | select-String 'ClearTextPassword' -SimpleMatch).ToString()
        rm -force c:tempsecpol.cfg -confirm:$false
        return @{Result = $str}     
    }    

问题是,当你调用一个外部命令(如secedit)时,如果这个命令(这是很自然的),它写入stdout的所有内容都会作为输出返回。但是,如果没有将其捕获到变量中,它将进一步传递到脚本块的输出中。return的说法也有点误导——它的意思不是"只返回这个东西",而是"把这个东西写到输出流,然后返回"。

这意味着您的原始GetScript不会返回单个哈希表,而是返回如下所示的数组:

@(
  "some-output-from-secedit",
  @{ Result = $str }
)

将外部命令的输出分配给变量(在这种情况下我使用$null来表示我想丢弃它)将防止它弄乱脚本块的输出。

另一种方法是将命令的输出重定向到Write-Verbose(如果您有兴趣阅读它)或$null(如果您不在乎):

secedit /export /cfg c:tempsecpol.cfg | write-verbose

您可以尝试像这样修改getscript块吗:

GetScript   = {
start-process secedit -ArgumentList '/export /cfg c:tempsecpol.cfg' -Wait
$str = (Get-Content 'c:tempsecpol.cfg' | select-String 'ClearTextPassword' -SimpleMatch).ToString()
rm -force c:tempsecpol.cfg -confirm:$false
return @{Result = $str}     
}

最新更新