Hacker News new | ask | show | jobs
by kabdib 3204 days ago
Here's another absolutely classis interaction with PowerShell. Let's make a list of strings; I'm partly interested in what CSV conversion does to values that already have commas.

    PS> $x = @('a', 'b', 'c', 'd,xx', 'e')

    PS> $x
    a
    b
    c
    d,xx
    e
Okay, that's great. Now:

    PS> $x | ConvertTo-json
    [
        "a",
        "b",
        "c",
        "d,xx",
        "e"
    ]
Hey, conversion to JSON works! But let's try the CSV conversion:

    PS > $x | ConvertTo-Csv
    #TYPE System.String
    "Length"
    "1"
    "1"
    "1"
    "4"
    "1"
... and I think I just died a little inside. I didn't even get to answer the original question I had about escaping separators. I have no earthly idea why PowerShell decided to spew the lengths of the elements rather than the values, or what the hell the other gorp in the output is.

The official documentation is not much help. I could go do some research on StackOverflow and so forth, but . . . I've lost the will to live. For this little exercise I've reached the point of uncaring.

This is basically my everyday interaction with PowerShell; try out something new, have it fail in a way that this LISP / Python / C++ / etc. veteran would never expect, and spend 20 minutes or maybe a whole bloody day researching why, or working around the behavior with other tools. I could become an expert in PowerShell, but I'm not interested, I just want things to work in reasonable ways. I've got shit to do. [I'm writing this HN post because in ten minutes I get to dive into some more PowerShell]

PowerShell has repeatedly failed the "reasonable expectation" test. I can't depend on it to be a lightweight and useful tool. Instead, every time I use it I can expect to spend 60 percent of my time working around capricious nonsense, dredging through postings by other people who have thankfully preceded me.

2 comments

It's about knowing what the function expects to receive.

What you got seems unexpected initially, but as you read the doc on this function (which took me a good 20 secs) you may think it is indeed well conceived, and realize that it was weird to expect passing an array of strings to it and expect it to work.. I don't even know what it should've done.

Should it have given you a single line of comma separated values? But then what should you give to the function to have multiple lines of csv? An array of array of strings?

"$arrayOfObjects | ConvertTo-Csv" will create one row per object in the array, with a column for each public field of the object. That's exactly what happened, and it seems like a reasonable behavior to me.

Do you have an alternative? Maybe for the edge case where the contents of the CSV is a list of primitives, it should give you a "Value" column? Or did you expect that, given an array of stuff, the best approach is to encode the whole array in a single CSV row?