【发布时间】: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