return an a single string as an array

For what it is worth, I would like this two work in posershell version 2 for compatibility

I want to write a function that will return a single string as an array. How ever i try it, it returns it as a string

function my-test{
    $a = @("fff")
    return $a

I would have expected(wrongly) that this would return an array, but it returns a string. How can I get this to return an array?

When you output items from a PowerShell function (even with the return statement), it will enumerate collections and send them down the output stream one at a time. That’s usually what you want to happen, but sometimes that’s not the case.

In PowerShell v3 or later, you can use this:

Write-Output -NoEnumerate $a

Which is nice and clear. For v2 compatibility, you need to use the unary comma operator. This wraps your array in another array, so when PowerShell enumerates the outer array, it still sends your inner one intact down the pipeline:

return ,$a

Much less clear in terms of code readability, but it’s all you’ve got prior to v3. (It’s also quite a bit faster than calling Write-Output, if you have performance hotspots that need tuning at some point.)

Thanks Dave!