How do I represent properties of PowerShell objects in an inline string without workarounds?

StackOverflow https://stackoverflow.com/questions/23139230

  •  05-07-2023
  •  | 
  •  

Pergunta

How do I represent properties of objects in an inline string without workarounds? I know that I can represent complex variable names, names with dots, like so: ${My bad.variable-name} so why wouldn't it work for object properties ${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
}
Foi útil?

Solução

{} makes it possible to specify a "special" variable name only. To access an object's properties inside a string, you need to use a subexpression @(), like

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

Subexpressions are evaluated before string creation, so they will be replaced with the values of the script inside $()

Outras dicas

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top