1

I need to determine where to load "Company" form a configuration file.

<config>
  <username>$env:username</username>
  <company>$User.Company</company>
</config>

After loading the config file:

$ConfigFile=[xml](Get-Content $ConfigFileName)
$ConfigFile.config.Company

It returns:

$User.Company

"$User" is another object, where $User.Company equals:

ACME Company

I had tried:

$Company=$ExecutionContext.InvokeCommand.ExpandString($ConfigFile.config.Company)

But that only expands "$User", not "$User.Company".

How do I set $Company to $Config.config.Company that will result in a string "ACME Company"?

Gajanan Kulkarni
  • 697
  • 6
  • 22
YoungKai
  • 13
  • 3

1 Answers1

0

$ExecutionContext.InvokeCommand.ExpandString() performs the same kind of string expansion (interpolation) that PowerShell implicitly performs on "...", i.e., double-quoted strings.

Inside a double-quoted string, expanding an expression such as $User.Company - as opposed to a mere variable reference (e.g., $User) - requires that the expression be enclosed in $(...) - otherwise, as you've experienced $User, is expanded by itself, with .Company being considered a literal.

See this answer for an overview of PowerShell's string-expansion rules.

You have two options:

That said, both solutions ultimately blindly execute any expressions / statements contained in the string, so you should only do that with input you trust.

To put it all together:

# Sample $User object
$User = [pscustomobject] @{ Company = 'ACME Company' }

# Read the XML
$ConfigFile = [xml] '<config>
<username>$env:username</username>
<company>$User.Company</company>
</config>'

# Pass the element value of interest to $ExecutionContext.InvokeCommand.ExpandString
# after enclosing it in '$(...)' via -f, the string-formatting operator.
$ExecutionContext.InvokeCommand.ExpandString('$({0})' -f $ConfigFile.config.Company)

The above yields:

ACME Company
mklement0
  • 382,024
  • 64
  • 607
  • 775