return an a single string as an array

Welcome Forums General PowerShell Q&A return an a single string as an array

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
3 years ago.

  • Author
    Posts
  • #31557

    Participant
    Points: 1
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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

    Participant
    Points: 1
    Rank: Member

    Thanks Dave!

The topic ‘return an a single string as an array’ is closed to new replies.