Monday, June 15, 2020

Get-Content string values have file information stapled to them

Today I wrote a quick PowerShell script that involved reading lines from a file with Get-Content and putting each into an object that was later serialized with ConvertTo-Json. To my surprise, instead of lines being serialized as standard JSON strings, they become JSON objects with a "value" property and several others describing the file the line came from. I checked the line variable's type with .GetType() and it was a standard string. Piping it to Get-Member, however, showed that it had several NoteProperty members. Note properties can be associated with arbitrary objects. They don't touch the actual .NET object, but PowerShell keeps track of them and ConvertTo-Json serializes them. It's strange (IMO) for Get-Content to staple this information to every line string since I'd expect transformation to a different serialization format to be a common task. I worked around it by calling .ToString() on the annotated string object to get an unannotated copy.

No comments:

Post a Comment