2

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!

1
  • 3
    Have you tried: $field.data.'data_numeric-enhanced' ? Commented Aug 12, 2019 at 13:38

2 Answers 2

4

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

This should work:

$field.data.'data_numeric-enhanced'

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer! I'd like to point anyone reading this to Mathias's answer as well since it describes the behavior of the interpreter that allows this to work.
2

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

2 Comments

Mathias this isn't the first time you've come to my rescue and I wanted to say thank you. Your answers and explanations are invaluable on this site. I may mark the other answer as the solution even though your answer contains a better explanation on the reasoning. The other user just answered in comments first and I'm not sure what the protocol is there.
@MarleyStacy Thank you, great to hear my efforts are worth-while :) don't worry, jrider indeed deserves the accept

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.