Marley Stacy
Marley Stacy

Reputation: 100

Escaping a Dash in XML Element Name With Powershell

I'm trying to refer to some XML elements in a list of parent objects using Powershell, but when I reach the point in my variable declaration that includes a hyphen ('-') the rest of the declaration is read as an argument.

I've tried casting the variable name as a string, enclosing it in single and double quotes as well as parentheses. None have worked.

$imessagelist = $xml.pnet_message_history_packet_response.IMessage
$formidlist = $imessage.formdata.form_id
$fieldlist = $imessage.formdata.im_field
$fieldcontent = $field.data.data_numeric-enhanced

All the references like formidlist and fieldlist let me append '.formdata.im_field' to the list of items and retrieve the data. The only one that doesn't work is the one with a dash in it. The error received is as follows:

At C:\Temps-v0.1.ps1:36 char:69
+ ...                     $fieldcontent = $field.data.data_numeric-enhanced
+                                                                 ~~~~~~~~~
Unexpected token '-enhanced' in expression or statement.

I can't figure out how to escape the dash and get the value in the field named data_numeric-enhanced. Any advice would be very welcome!

Upvotes: 2

Views: 2048

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

In version 3 or 4 (can't remember), the . member expression operator was changed to accept any string expression as its right-hand operand, so you can qualify member names with quotation marks:

$field.data.'data_numeric-enhanced'

or

$field.data.$(@('data_numeric'; Write-Host "anything resolving to the member name can go in here"; '-enhanced') -join '')

Upvotes: 2

jrider
jrider

Reputation: 1630

You should be able to access the property by encapsulating the last member.

This should work:

$field.data.'data_numeric-enhanced'

Upvotes: 4

Related Questions