【问题标题】:Invoking a function indirectly, via a variable containing the function name通过包含函数名称的变量间接调用函数
【发布时间】:2017-08-20 11:30:54
【问题描述】:

我正在将一个 XML 节点导入到变量 XmlInstallNode 中,然后动态构建我要调用的函数。

如果我直接通过函数名调用函数,一切都很好,但是如果在调用命令中使用 $functionName 调用它,那么当参数 -App - 应该是 System.Xml 时,它会转换为字符串。 XmlLinkedNode。我已经尝试过使用 Invoke-Expressions 和 Invoke-Command 进行转换并使用不同的方法,但没有成功......

我得到了这个错误,这有点道理: 无法处理参数“App”的参数转换。无法将“System.String”类型的“$app”值转换为“System.Xml.XmlElement”类型

function global:XtrInstall{
try
{
    $error=$false
    XtrLog -Level INFO -FunctionName $MyInvocation.MyCommand -Msg "Installing Apps..."

    XtrLog -Level DEBUG -FunctionName $MyInvocation.MyCommand -Msg "Getting available Apps from config file."
    $XmlInstallNode=XtrGet-XmlInstall

    if($XmlInstallNode.Apps)
    {        
        foreach($app in $XmlInstallNode.apps.app)
        {
            $functionName = "$("XtrInstall-")$($app.Name)"
            XtrLog -Level DEBUG -FunctionName $MyInvocation.MyCommand -Msg "$("Building function name: ")$($functionName)"

            if (Get-Command $functionName -errorAction SilentlyContinue)
            {
                XtrLog -Level DEBUG -FunctionName $MyInvocation.MyCommand -Msg "$("Invoking App Install function ")$($functionName)"
                $command = "$($functionName)$(" -App")"
                $error = Invoke-Command -ScriptBlock { Invoke-Expression -Command $command} -ArgumentList $app                    
            }
            else
            {
                XtrLog -Level FATAL -FunctionName $MyInvocation.MyCommand -Msg "$("App Install Function " )$($functionName)$(" not found. See App name (e.g.'XtrInstall-Aplication')")"
                return $true
            }
        }
    }
    else
    {
        XtrLog -Level WARN -FunctionName $MyInvocation.MyCommand -Msg "No Apps detected in Config file."
        $error=$true
    }
}
catch
{
    XtrLog -Level FATAL -FunctionName $MyInvocation.MyCommand -Msg $_.Exception.Message
    $error=$true
}
return $error
}

我调用的函数是:

    function global:XtrInstall-Filesite()
    {
    Param(
        [Parameter(Mandatory=$true)]
        [Xml.XmlElement]$App
    )
        //DO STUFF
    }

如何按原样传递参数?

【问题讨论】:

    标签: powershell parameter-passing indirection


    【解决方案1】:

    无需在字符串中构建(部分)命令并使用Invoke-Expression,甚至Invoke-Command

    请尝试以下方法:

    $error = & $functionName -App $app                    
    
    • &,PowerShell 的 call operator,可用于调用 name 存储在 variable 中的任何命令。
      • (您还需要它来调用外部实用程序,其路径必须引用,因为其中包含空格或其他具有特殊含义的字符;例如,
        & 'c:\path\to\some folder\some.exe')。李>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-01
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 2011-11-16
      相关资源
      最近更新 更多