Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 258
Kevin Hoang Avatar asked Apr 16 '15 04:04

Kevin Hoang


1 Answers

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
like image 73
majkinetor Avatar answered Sep 29 '22 02:09

majkinetor