简体   繁体   中英

ExecutionContext.InvokeCommand.ExpandString throws exception in PowerShell 4.0

I have a script as below

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

After this line, the value of $newValue is

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

In the loop, I call ExpandString

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

It throws exception

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

But when I try to input hard-code string, it returns expected result without exception

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

The value of $partnerSpecificValue is

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

Does anyone know a workaround to resolve this bug? Thank you very much. I am running PowerShell v4.0 on Windows Server 2012 R2.

ExpandString is problematic and doesn't work correctly in general case. I use this method instead:

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

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

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM