3

Suppose I have an array with random values in it, like for instance

$a=@(0..5) 

and I would like to format that array in a string like this :

{0,1,2,3,4}

comma separated values between curly braces. The "catch" is that I don't know in advance the size of the array, and in some cases, when there's only one record the type won't be array but psobject, when it's a unique PSObject I don't need curly braces and commas, I want to leave it as it is.

Thanks!

4
  • Have you tried anything for this? Commented Nov 23, 2015 at 19:06
  • 1
    For the array case, it's pretty simple. "{$($a -join ',')}" I'm not sure I understand the "in some cases" clause. Can you elaborate on your PSObjects? You probably want to switch on if ($a -is [PSObject]) Commented Nov 23, 2015 at 19:10
  • 2
    '{{{0}}}' -f ($a -join ',') Commented Nov 23, 2015 at 19:10
  • 2
    There's also the Perl-ish way: $ofs=','; "{$a}" Commented Nov 23, 2015 at 22:13

1 Answer 1

1

I would go for this (if statement on the input object type, and use of @beatcracker's method) :

Code :

//insert an array and a custom object in an input array
$input = @(@(0, 1, 2, 3, 4, 5),
           [PSCustomObject]@{ title = "My"; first = "Custom"; last = "Object" })

//an empty output array
$output = @()

//foreach item in the input array
foreach($item in $input) {

    //if item base type is array
    if($item.GetType().BaseType.Name -eq "Array") {

        //process and add to output array
        $output += "{{{0}}}" -f ($item -join ",")
    } else {

        //add to output array as-is
        $output += $item
    }
}

//echo output array
$output

Output :

{0,1,2,3,4,5}

title first  last  
----- -----  ----  
My    Custom Object

Info : {0} is a placeholder for the 1st value after -f, ($item -join ",") ; the next one would have been {1} (more info here).

Additional curly brackets are there to escape surrounding curly brackets to make sure they appear in the final string.

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer looks great! :) Would you mind explaining what "{{{0}}}" stands for? Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.