【问题标题】:Calling a Function from a Script block in a DSC configuration从 DSC 配置中的脚本块调用函数
【发布时间】:2022-04-22 03:30:20
【问题描述】:

我在 Windows 10 上的 dsc 配置有问题。我必须定义一个脚本块,因为考虑到它需要服务器 sku,我无法使用 dsc 安装 WindowsIIS。以下代码是绕过它的方法示例(排序),但由于某种原因,我无法从脚本块调用我的模块或函数。看看:

Configuration update-settings
{

    $hostname = $env:COMPUTERNAME

    Node $hostname
    {
        Script whatever
        {
            GetScript = { return @{'Result' = 'something'} }
            TestScript = { return $false }

            # problem is here:
            SetScript = { run-myfunction -args something }
        }
    }
}

我在别处有一个 psm1 文件,即使我在我的 dsc 中执行 Import-Module C:\MyFolder\PSModules\run-myfunctions.psm1 -force,它仍然给我以下错误:

PowerShell DSC resource MSFT_ScriptResource  failed to execute Set-TargetResource functionality with error message: The term 'run-myfunction' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a 
path was included, verify that the path is correct and try again.
    + CategoryInfo          : InvalidOperation: (:) [], CimException
    + FullyQualifiedErrorId : ProviderOperationExecutionFailure
    + PSComputerName        : DESKTOPofMe

The SendConfigurationApply function did not succeed.
    + CategoryInfo          : NotSpecified: (root/Microsoft/...gurationManager:String) [], CimException
    + FullyQualifiedErrorId : MI RESULT 1
    + PSComputerName        : DESKTOPofMe

仅供参考,我确实正确运行并导出了我的 powershell 模块,并且可以在命令行上使用run-myfunctionrun-myfunction2 等访问它们。

任何帮助将不胜感激,谢谢:)

【问题讨论】:

  • Import-Module cmdlet 不会抛出任何错误吗?
  • 不,根本没有:)
  • 我认为您遇到的问题与 DSC 脚本资源有关,该资源在抛出到 Invoke-Command 的脚本块中执行脚本,您可以通过检查 C:\Windows\ 的 psm1 来查看它是如何执行的SysWOW64\WindowsPowerShell\v1.0\Modules\PSDesiredStateConfiguration\DSCResources\MSFT_ScriptResource 在你的机器上。你也可以检查这个问题,因为它有点相同的问题:stackoverflow.com/questions/14441800/…

标签: powershell dsc


【解决方案1】:

要记住的重要一点是 DSC 不是 Powershell - 您可以通过 Script 资源运行 Powershell 命令或脚本,但在 Script 资源中调用的任何命令都不知道其脚本根目录或路径.

如果您的 run-myfunction 函数暴露在 .ps1 文件中,我发现这种语法可以很好地工作,尽管您的 run-myfunction 代码将需要对它的任何其他资源或模块使用绝对路径参考,以便可靠地找到它们:

Script Run-MyFunction {
    SetScript = {
                & "C:\path\to\script\RunMyFunction.ps1" -ParamName "paramValue"
    }
    ...
}

执行此操作的标准方法是为run-myfunction 创建一个 DSC 资源,并将其作为您节点的 DSC 配置的一部分进行调用。

【讨论】:

    猜你喜欢
    • 2018-03-04
    • 1970-01-01
    • 2023-03-17
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 2017-11-09
    • 1970-01-01
    相关资源
    最近更新 更多