Search code examples
powershellpowershell-2.0powershell-3.0azure-powershellpowershell-4.0

while using arraylist how to display objects in powershell


$result = New-Object System.Collections.ArrayList
ForEach ($repoElement in $Repo.value)
{
 $repoId = $repoElement.id
 $BranchCreatorUrl = "https://dev.azure.com/xyz/_apis/git/repositories/$repoId/refs?api-version=6.1-preview.1"
 $CreateorInfo = (Invoke-RestMethod -Uri $BranchCreatorUrl -Method Get -UseDefaultCredential -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)})
 $url1= "https://dev.azure.com/xyz/_apis/policy/configurations?api-version=4.1"
 $response = (Invoke-RestMethod -Uri $url1 -Method Get -UseDefaultCredential -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)})
 
 $obj=[pscustomobject]@{
            RepositoryName = $repoElement.name
            RepositoryId = $repoId
            BranchName = $CreateorInfo.value.name
            PolicyName = $response.value.type.displayname
        }
        $result += $obj
        
}
Write-Output $result


The above code gives an output 

enter image description here

I want to show all the branch name as string and not in the form of object ie this way {..,...,...,..}


Solution

  • If this is just about for-display formatting, i.e. what is shown in the implicitly table-formatted display output, you can call Format-Table explicitly and use a calculated column to apply custom formatting to the BranchName column:

    # Sample result.
    $result = [pscustomobject]@{
      RepositoryName = 'name'
      RepositoryId = 'id'
      BranchName = 'branch1', 'branch2', 'branch3'
      PolicyName = 'policy'
    }
    
    # Use explicit Format-Table formatting with custom formatting of the 
    # 'BranchName' column.
    $result | Format-Table RepositoryName, 
                           RepositoryId, 
                           @{ n='BranchName'; e={ $_.BranchName -join ', ' } },
                           PolicyName
    

    The above yields a tabular display whose BranchName column doesn't have the enclosing { ... }, which PowerShell uses to indicate that the column value is an array (perhaps confusingly, because it looks like a script block):

    RepositoryName RepositoryId BranchName                PolicyName
    -------------- ------------ ----------                ----------
    name           id           branch1, branch2, branch3 policy