如何在没有解决方法的情况下在内联字符串中表示PowerShell对象的属性?

时间:2014-04-17 17:03:35

标签: powershell powershell-v3.0

如何在没有变通方法的情况下表示内联字符串中对象的属性? 我知道我可以表示复杂的变量名,带点的名称,如下所示:$ {My bad.variable-name}那么为什么它不能用于对象属性$ {Xml.Node.Value}?

[xml]$appConfig = @"
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="TerminalID" value="999999" />
        <add key="ClientID" value="TESTTEST" />
    </appSettings>
</configuration>
"@

$appSettings = Select-Xml $appConfig -XPath '//add'
foreach ($setting in $appSettings)
{
    $setting.Node.key #works
    $setting.Node.value #works
    #I want to display above values as part of a string
    "Setting: $setting.Node.key = Value: $setting.Node.value"  
    #ah, I need curly braces around the variable

    ${setting.Node.key} #doesn't work
    ${setting.Node.value} #doesn't work
    "Setting: ${setting.Node.key} = Value: ${setting.Node.value}"  #definately doesn't work

    #I think it's because I'm referring to the property (key) of a property (Node) of a variable (settting)
    $setting | gm -MemberType Property
    $setting.Node | gm -MemberType Property

    #I can solve with string::format
    [string]::format("Setting: {0} = Value: {1}", $setting.Node.key, $setting.Node.value)

    #But I like inline strings in powershell so I have to do this, how can I do it inline without reassigning to another variable?
    $key = $setting.Node.key
    $value = $setting.Node.value
    "Setting: $key = Value: $value"  #works
}

2 个答案:

答案 0 :(得分:3)

{}可以指定&#34;特殊&#34;仅变量名称。要访问字符串中的对象属性,需要使用子表达式@(),如

"Setting: $($setting.Node.key) = Value: $($setting.Node.value)"

在创建字符串之前评估Subexpressions,因此它们将替换为$()内的脚本值

答案 1 :(得分:0)