在使用 arraylist 时如何在 powershell 中显示对象

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 

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

如果这只是关于显示格式,即在隐式 table 格式的显示输出中显示的内容,您可以调用 Format-Table explicitly and use a 将自定义格式应用于 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