Sunday, 22 February 2009

PowerShell : Dealing with a ‘-‘ literal in data

Lets say for example that you are parsing an xml document with PowerShell and one of the nodes is called “direct-message” as in the Twitter REST API, and using the cool PowerShell dot notation for navigating the document you might expect that you can just do this


[array]$messages = $xml.direct-messages.direct_message


but sadly you will just get this error


You must provide a value expression on the right-hand side of the '-' operator.

At C:\Utils\TwitterClient\TwitterClient.ps1:12 char:38


+ [array]$messages = $xml.direct- <<<< messages.direct_message



Basically PowerShell is seeing the ‘–’ and treating it as an operator.. but all is not lost because you can simply just escape the offending node in single quotes, as such :




[array]$messages = $directXml.'direct-messages'.direct_message

No comments:

Post a Comment