Powershell modules, json conversion quirk

I came across this powershell quirk today and thought I should share it with anyone else who might be writing powershell ansible modules.

It seems there is a bug, or at least an inconsistency in the behaviour of ConvertTo-Json

It appears that it fails to convert strings to json if they end with a trailing backslash, which is a hazard for windows folder paths which can be expressed with a trailing backslash, e.g c:\temp\

What is strange is that if you use the -Compress option with ConvertTo-Json the string seems to convert ok.

I wound up using

$message = $message.TrimEnd("") to clean up the affected string in my custom module, but I’m considering whether it would be wise to add -Compress to the two places it occurs in lib/ansible/module_utils/powershell.ps1. This would make ansible a bit more robust to modules without sanitized output - I suppose at the expense of the overhead of ‘compressing’ the json (which seems to just be quoting and removing whitespace).

The issue is described here:

https://connect.microsoft.com/PowerShell/feedback/details/869768/powershell-convertto-json-error-when-has-string-with-trailing-backslash

All the best,

Jon

i would be fine with always compressing the json, most of the time we
reformat the output at the ansible command line anyways.

We use the -Compress option for some of our custom modules and we have not have issues for now.

+1 for making it by default so that trailing backslash and some other issues are fixed.

Ok. I was about to create PR to make the change but noticed that
version of module_utils/powershell.ps1 in v2 is older than the v1 code.

I’m thinking perhaps best to leave this until v2 is current.

Jon

files seem to be the same now, feel free to update one and we'll make
sure changes percolate to the other.

Will do

Still seems to be a small difference to me (different checksum algorithm being used), but I have pushed to the ‘v1’ version PR is https://github.com/ansible/ansible/pull/11090

Jon