return an a single string as an array

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Shane Lindberg Shane Lindberg 1 year, 4 months ago.

  • Author
    Posts
  • #31557
    Profile photo of Shane Lindberg
    Shane Lindberg
    Participant

    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?

  • #31558
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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.)

  • #31559
    Profile photo of Shane Lindberg
    Shane Lindberg
    Participant

    Thanks Dave!

You must be logged in to reply to this topic.