首页 > 解决方案 > Powershell - 来自 XML 的对象引用

问题描述

我需要确定从配置文件加载“公司”的位置。

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

加载配置文件后:

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

它返回:

$User.Company

"$User" 是另一个对象,其中 $User.Company 等于:

ACME Company

我试过:

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

但这只会扩展“$User”,而不是“$User.Company”。

如何将 $Company 设置为 $Config.config.Company 以生成字符串“ACME Company”?

标签: xmlpowershellobject

解决方案


$ExecutionContext.InvokeCommand.ExpandString()执行与PowerShell 隐式执行的相同类型的字符串扩展(插值)"...",即双引号字符串

在双引号字符串中,扩展诸如$User.Company- 而不是单纯的变量引用(例如,$User)之类的表达式需要将表达式包含在$(...)- 否则,正如您所经历的那样,它本身$User会被扩展,并被视为字面意思.Company

有关PowerShell 的字符串扩展规则的概述,请参阅此答案。

你有两个选择:

  • 在将字符串的内容$(...)传递给之前将其包含在其中$ExecutionContext.InvokeCommand.ExpandString()

  • 改为使用Invoke-Expression,但请注意通常应避免使用 Invoke-Expression

也就是说,这两种解决方案最终都会盲目地执行字符串中包含的任何表达式/语句,因此您应该只使用您信任的输入来执行此操作。

把它们放在一起:

# 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)

以上产生:

ACME Company

推荐阅读