ExecutionContext.InvokeCommand.ExpandString 在 PowerShell 4.0 中抛出异常

ExecutionContext.InvokeCommand.ExpandString throws exception in PowerShell 4.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

但是当我尝试输入硬编码字符串时,它 returns 预期结果无一例外

$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。

我有解决此错误的方法。

https://social.technet.microsoft.com/Forums/en-US/5efc52d2-619c-4063-9a47-bc646c45e882/executioncontextinvokecommandexpandstring-throws-exception-in-powershell-40?forum=winserverpowershell

ExpandString 有问题,在一般情况下不能正常工作。我改为使用此方法:

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

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

示例:

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