ExecutionContext.InvokeCommand.ExpandString在PowerShell 4.0中引发异常

时间:2015-04-16 04:05:36

标签: powershell powershell-v4.0

我有一个脚本如下

[string] $ newValue = Get-ConfigurationByType $ setting.Value

在此行之后,$ newValue的值为

"http://ST-$($partner.Alias).vardiaforsakring.se/CardPaymentAgreementCallback.aspx"

在循环中,我调用ExpandString

foreach ($partner in $partners) { $partnerSpecificValue =$ExecutionContext.InvokeCommand.ExpandString($newValue) }

抛出异常

Exception calling "ExpandString" with "1" argument(s): "Object reference not set to an instance of an object."
At C:\Programs\Drops\Hydra_SE_v1.28\HydraDeploymentFunctions.ps1:342 char:5
+                 $partnerSpecificValue = $ExecutionContext.InvokeCommand.ExpandString($newVal ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NullReferenceException

但是当我尝试输入硬编码字符串时,它会毫无例外地返回预期结果

$partnerSpecificValue =$ExecutionContext.InvokeCommand.ExpandString("http://ST-$($partner.Alias).vardiaforsakring.se/CardPaymentAgreementCallback.aspx")

$ partnerSpecificValue的值是

http://ST-secure.vardiaforsakring.se/CardPaymentAgreementCallback.aspx

有没有人知道解决此错误的解决方法?非常感谢你。我在Windows Server 2012 R2上运行PowerShell v4.0。

2 个答案:

答案 0 :(得分:7)

ExpandString存在问题,在一般情况下无效。我改用这种方法:

function render() {
    [CmdletBinding()]
    param ( [parameter(ValueFromPipeline = $true)] [string] $str)

    "@`"`n$str`n`"@" | iex
}

示例:

$x=@{test='test'}
'Hashtable x contains value $($x.test)' | render

答案 1 :(得分:0)