使用arraylist时如何在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

我想将所有分支名称显示为字符串而不是对象的形式,即这种方式{..,...,..}

解决方法

如果这只是用于显示格式,即隐式表格格式显示输出中显示的内容,您可以调用 Format-Table 显式 并使用 calculated column将自定义格式应用于 BranchName 列:

# 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

上面产生了一个表格显示,其 BranchName 列没有封闭的 { ... },PowerShell 使用它来指示列值是一个 数组(可能会令人困惑,因为它看起来像一个脚本块):

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