0

I've been working on a script to get the user list from an Azure DevOps organization, and then populate an array with selected properties of those users, and then create a CSV. However, when I export my results to CSV, the properties are in a strange order (as opposed to the order I called them in the script). Here's the code:

[string]$PAT = "MyPATLooksLikeRandomCharacters"
[string]$Organization = "https://dev.azure.com/My-Organization-Name"

$UserGroups = @()

echo $PAT | az devops login --org $Organization

# For now, select just 3 users from the list, for testing purposes.
$allUsers = az devops user list --org $Organization --skip 25 --top 3 | ConvertFrom-Json

foreach($au in $allUsers.members)
{
    $UserGroups += New-Object -TypeName PSObject -Property @{
        Name        = $au.user.displayName
        Email       = $au.user.principalName
        AccessLevel = $au.accessLevel.licenseDisplayName
        Status      = $au.accessLevel.status
        Created     = $au.dateCreated
        LastAccess  = $au.lastAccessedDate
    }
}

$UserGroups | Export-Csv -Path c:\temp\users.csv 

When I open the CSV, the columns are (from left to right):

Email, AccessLevel, Status, LastAccess, Name, Created

I've tried shuffling the order of the properties, but it doesn't change the order. I've also tried changing the names (instead of "Name" and "Email" I tried names like "Property1" and "Property2"). It still changed the order, albeit in a completely different way. (Clearly I'm missing something important about what's really happening during the population of the array.)

My goal is to have the CSV columns appear in the same order they're called in the code. Is there a way to populate the array to ensure that happens?

  • Does this answer your question ? https://stackoverflow.com/questions/70450959/powershell-is-re-arranging-my-columns-and-i-cant-figure-out-why/70451048#70451048 – Santiago Squarzon Jul 15 '22 at 01:18
  • 1
    Also try to avoid `@()` and `+=`, this is very inefficient. See this answer for details: https://stackoverflow.com/a/60708579/15339544 \\ `$UserGroups = foreach(...` and removing `$UserGroups +=` in summary is far more efficient code – Santiago Squarzon Jul 15 '22 at 01:20
  • 1
    Thank you, Santiago. When I checked in this morning, the web interface here kindly pointed out that this question has already been answered, at exactly the page you referenced. I'm brand new here, and very new to PowerShell as well, so I appreciate your reply. I had also read about the inefficiency of +=. For now my script is returning about 500 results and is only using about 2% CPU for about 5 seconds, so I can live with it - but I do intend to learn the more efficient technique someday when I can understand it. Thanks again! –  Jul 15 '22 at 14:07

0 Answers0