Moving away from static array to lists

Hi all,

I asked a team member to produce a script which would get all the staff for a given manager.
(There's a similar post up at the moment for AD DS, but our need was for Azure AD.)

He produced the following script - which is entirely functional:

param (
    [Parameter (Mandatory = $true)]
    [string] $targetManager
)

$global:Output = @()
function Get-DirectReports ($targetManager)   
{  
        $reports = Get-AzureADUserDirectReport -ObjectId $targetManager | where{$_.ExtensionProperty["employeeId"] -ne $null} | select Userprincipalname, DisplayName, Mail, @{N="EmployeeId";E={$_.ExtensionProperty["employeeId"]} }
        ForEach ($user in $reports) { 
        $Obj =  New-Object psobject -Property @{
        UserUPN = $User.UserPrincipalName
        UserMail = $User.Mail
        UserDisplayName = $User.DisplayName
        EmpID = $user.EmployeeId
        Manager = $manager} 
        $global:output= $global:output + $obj
        
        Get-DirectReports $user.UserPrincipalName
        
    }
   $Output | Export-csv $home\desktop\DirectReports_manager.csv -NoTypeInformation
}   
Get-DirectReports $targetManager

But, having seen some PoSH gurus talking about moving away from arrays and +=, I thought I'd try to do this using System.Collections.Generic.List and its .Add method

The results were a total shambles, and after several hours banging my head against the problem, I gave up somewhat demoralised.

The main issue was that I could not find a way to reference the data in $Output in such a way as to produce the same column output as the original code achieves.

Can anyone offer code which would use System.Collections.Generic.List, instead of an array created using = @() but which can output data that can be pushed through to Export-Csv?

I really struggle with data types sometimes, so I'm hoping that seeing an example on this will help me further my knowledge.

Thanks in advance

Posted Feb 10, 2023, 9:42 AM UTC

319
Loading comments…