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

Kev*_*ang 5 powershell 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

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

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

$ partnerSpecificValue的值是

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

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

maj*_*tor 7

ExpandString是有问题的,并且在一般情况下不能正常工作.我改用这种方法:

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

    "@`"`n$str`n`"@" | iex
}
Run Code Online (Sandbox Code Playgroud)

例:

$x=@{test='test'}
'Hashtable x contains value $($x.test)' | render
Run Code Online (Sandbox Code Playgroud)

  • 它将HERE DOC字符串发送到Invoke-Expression.该字符串可以包含Posh变量. (2认同)