xml - 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”?
解决方案
$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
推荐阅读
- r - 将SPSS中的标签添加为R中的列名
- c# - 从另一个 Combobox 中选择时更改另一个 Combobox Item 列表
- java - 杰克逊:反序列化 XML 在列表中提供了太多元素
- asp.net - 从复选框列表向多个号码发送短信
- javascript - JavaScript 按可空布尔值排序数组,然后是字符串
- installation - 无法在 Windows 10 版本 1903 上安装 Chocolatey
- asp.net - 子目录的 web 配置设置和身份验证问题
- sql - 我们可以在选择语句中使用 Map(col1,col2)
- c++ - 如何在 C++ 中使用 setiosflags 将十进制数打印为八进制数
- rxjs - Rxjs - 如何让 concatMap 排队的 observables?