Stop Using +=, or How to Add Data to an Array

If you are coming to PowerShell from another scripting language you may fall into this coding trap. I know I did when I was first learning the ropes. It’s easy to miss too since your system probably won’t feel the load when running lighter tasks. However, this trick may save you when you are running 1000+ item reports. So let’s get into it.

For this example, let’s say you are asked to build a report of all the processes running on a system. Now you might have some prior scripting knowledge and so You whip up some code similar to the example below. Except there’s one problem. It doesn’t run…

$processes = Get-process
foreach ($process in $processes) {
    $properties= [ordered]@{
        Name = $process.Name
        ID = $process.ID
    }
    $object = new-object -type PSObject -property $properties
    $report += $object
}
Write-output $report

The PowerShell Prompt will yell at you ALOT saying “A hash table can only be added to another hash table.” So let’s look. After if I run that script in the prompt I’ll be able to inspect $report as we see below.

PS C:\> $report | get-member


   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
ID          NoteProperty int ID=10124
Name        NoteProperty string Name=audiodg

So our problem is how PowerShell handles typecasting of $report. We want it to be an array. However, after we “add” (+=) $object to it PowerShell makes $report a PSCustomObject. Then when we loop through again, PowerShell gets confused because you can’t add an object to an object. So it gives up and tosses an error. So how do we fix that?

$processes = Get-process

#################
$report = @()
#################

foreach ($process in $processes) {
    $properties= [ordered]@{
        Name = $process.Name
        ID = $process.ID
    }
    $object = new-object -type PSObject -property $properties
    $report += $object
}
Write-output $report

We’ll go ahead and explicitly case $report as an array by using $report = @(). That solves the issue and now the code runs. However, we are actually sacrificing some performance using this method of adding to an array.

Here’s what’s going on under the hood when we use += to add to an array in PowerShell. In the beginning, our array, $report, is created into memory as an empty array. Once PowerShell reaches the first iteration of += the following happens in memory. PowerShell allocates enough memory to store our current version of $report PLUS the data of the new iteration of $object. This is all happening while the old version of $report is still hanging out in memory. PowerShell then dumps the contents of $report into the new memory allocation block after that it then adds $object too. After all of that, it cleans up the old version of the $report array in memory.

This means every iteration of the foreach loop you end up with 2 copies of $report in memory. So while you are running through 100 tiny objects this isn’t an issue for memory on modern machines. However, once you run through 10,000, or even 100,000 or more objects it can be a little dicey. We’ll use the code below to demonstrate.

@(10, 100, 1000, 10000, 100000) | ForEach-Object {
    $IterationTime = Measure-Command {
        $array = @() #make a fresh array
        1..$_ | ForEach-Object {        #We make Powershell count from 1 to the current value in the iteration 10, 100, 1000 etc
            $array += $_ 
        }
    }
    $output = [pscustomobject]@{
        IterationTime  = $IterationTime.TotalMilliseconds 
        IterationCount = $_
    }
    $output
}
IterationTime IterationCount
------------- --------------
       3.5395             10
       5.5907            100
      41.9854           1000
    2775.8977          10000
  554277.5833         100000

So we don’t really have anything to compare those numbers to so lets run this. We’ll add to an array using Microsoft’s accepted solution using an ArrayList.

@(10, 100, 1000, 10000, 100000) | ForEach-Object {
    $IterationTime = Measure-Command {
        $array = [System.Collections.ArrayList]::new()
        1..$_ | ForEach-Object {
            $array.Add($_) 
        }
    }
    $output = [pscustomobject]@{
        IterationTime  = $IterationTime.TotalMilliseconds
        IterationCount = $_
    }
    $output
}
IterationTime IterationCount
------------- --------------
       3.3847             10
       3.4836            100
       9.7816           1000
      76.1171          10000
     764.8612         100000
Item Count+=ArrayList
103.5395 ms3.3847 ms
1005.5907 ms3.4836 ms
100041.9854 ms9.7816 ms
100002775.8977 ms76.1171 ms
100000449415.2217 ms764.8612 ms
Here’s the data consolidated to a table

The data looks pretty clear. Around 10,000 items you will start really feeling the performance hit at 2.7758 seconds for using += vs the .076 seconds using an ArrayList. Now keep in mind that we did absolutely no work on the data before adding it to the array. So, expect this issue to compound as you use += on arrays in the real world. Stick to ArrayLists if you want to add to Arrays.

After looking at the Arraylist example above, you might be thinking: “No way am I going to remember System.Collections.ArrayList]::new() when I go to make an array object”. If you are I have some good news for you. You don’t have to remember any of that. Just remember this simple trick instead.

@(10, 100, 1000, 10000, 100000) | ForEach-Object {
    $IterationTime = Measure-Command {
        $array = 1..$_ | ForEach-Object {
            write-output $_ 
        }
    }
    $output = [pscustomobject]@{
        IterationTime  = $IterationTime.TotalMilliseconds
        IterationCount = $_
    }
    $output
}
IterationTime IterationCount
------------- --------------
       3.6656             10
       9.8842            100
      54.5917           1000
     540.9592          10000
    4490.1897         100000

Welcome to the compromise. It’s a little slower than explicitly using ArrayLists, but you are still using an ArrayList. It’s slower for a couple of reasons. First, we are adding write-output to the loop which wasn’t there before. Second, there’s a little extra overhead while PowerShell figures out what’s we’re doing. Basically PowerShell notices we’re capturing the output of something. So to be clever PowerShell will spin up an ArrayList and capture the output of each loop. Once the loop is terminated PowerShell converts the completed ArrayList into an appropriate Object. In our case, we get a System.Int32.

PS C:\> $array | get-member


   TypeName: System.Int32

Name        MemberType   Definition
----        ----------   ----------
...

So to put it all together with our use case from the beginning. If we want to efficiently want to collect the object we’re creating for the Processes running on a system we’ll want to use the following.

$processes = Get-process
$report = foreach ($process in $processes) {
    $properties= [ordered]@{
        Name = $process.Name
        ID = $process.ID
    }
    $object = new-object -type PSObject -property $properties
    write-output $object
}
Write-output $report

This allows us to leverage ArrayLists effectively while cheating a little by not having to remember how to explicitly create an ArrayList variable. Now, when you spot someone using += in their code to add to an array just point them to this article and help change their mind 😀


Exchange Online Powershell v2- Not so fast?

So I’m really pumped this module exists. There’s finally a Exchange Online module that supports MFA that isn’t locked behind some non-standard installer buried in ECP. Nor is this module locked behind an Azure subscription. It’s published to the PowerShell Gallery like every other modern module. Even more exciting there’s new cmdlets available to speed up data collection. But do they live up the to hype?

According to Microsoft the primary goal of the new cmdlets is to speed up execution time. To reach that goal Microsoft slimmed down the returned objects for common cmdlets (get-mailbox, get-mailboxstatistics, etc). So now instead of 100s of properties get-mailbox returns 15. Get-MailboxStatistics now only returns 6 properties. You can get more, but now you have to explicitly ask for which ones you need using the -property parameter.

On paper this sounds awesome, and with some light editing you can take advantage of the new cmdlets. But first lets test it out on a simpler command.

PS C:\> Get-EXOMailBox -ResultSize Unlimited | select UserPrincipalName, RecipientTypeDetails

Here’s a relatively simple command. It’ll output the UPN and mailbox type (UserMailbox, SharedMailbox, RoomMailbox, etc.) for all mailboxes in the tenant. In my case I’m running this against a tenant with 155 mailboxes.

PS C:\> (get-mailbox -resultsize unlimited | select UserPrincipalName,RecipientTypeDetails).count
155

Not exactly the 1000s or 10,000s of accounts these new cmdlets are designed for but it will suit our needs today.

PS C:\> measure-command {get-mailbox -resultsize unlimited | select UserPrincipalName,RecipientTypeDetails}


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 4
Milliseconds      : 908
Ticks             : 49086056
TotalDays         : 5.68125648148148E-05
TotalHours        : 0.00136350155555556
TotalMinutes      : 0.0818100933333333
TotalSeconds      : 4.9086056
TotalMilliseconds : 4908.6056

So running everything the old way it takes us just shy of 5 seconds to collect data for 155 mailboxes. Next up, lets try the new way

PS C:\> measure-command {get-exomailbox -resultsize unlimited | select UserPrincipalName,RecipientTypeDetails}


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 7
Milliseconds      : 396
Ticks             : 73966512
TotalDays         : 8.56093888888889E-05
TotalHours        : 0.00205462533333333
TotalMinutes      : 0.12327752
TotalSeconds      : 7.3966512
TotalMilliseconds : 7396.6512

7.4 seconds. Hmmm…. That can’t be right. Can’t it? All we did is swap Get-Mailbox for the newer “faster” Get-EXOMailbox, yet it’s running ~2.5 seconds slower. Maybe we’ll see the true power of the EXO cmdlets in something more complex like a script?

#requires -module ExchangeOnlineManagement
$mailboxes = get-EXOmailbox -Resultsize unlimited
 
foreach ($mailbox in $mailboxes) {
     
    $MxboxStats = $mailbox | get-EXOmailboxstatistics
 
    if ($mailbox.ArchiveStatus -eq "Active" ) {
        $ArchiveMxboxStats = $mailbox | get-EXOmailboxstatistics -Archive
    }
    else {
        $ArchiveMxboxStats = $null
    }
    $properties = [ordered]@{
        DisplayName          = $mailbox.DisplayName
        PrimarySMTPAddress   = $mailbox.PrimarySMTPAddress
        UserPrincipalName    = $mailbox.UserPrincipalName
        Alias                = $mailbox.EmailAddresses
        RecipientTypeDetails = $mailbox.RecipientTypeDetails
        ItemCount            = $MxboxStats.ItemCount
        totalitemsize        = $MxboxStats.totalitemsize
        ArchiveItemCount     = $ArchiveMxboxStats.ItemCount
        ArchiveTotalItemSize = $ArchiveMxboxStats.totalitemsize
    }  
    $out = new-Object -Type PSCustomObject -Property $properties
    Write-Output $out
}

So lets level set real quick. This handy little script walks gets every mailbox, passes it through a foreach loop to then collect quick audit data of all the mailboxes. We grab their name, UPN, Primary email, mailbox type, number of mail items, total mailbox size, and if they have an archive total archive items, and archive size. I’ll get into this in a later post, but this thing isn’t quite ready to be a function. TL;DR I need to parameterize the mailbox input, but again that’s for another time. Lets see how long this takes to run.

PS C:\> measure-command {.\get-mailboxdatanew.ps1}


Days              : 0
Hours             : 0
Minutes           : 13
Seconds           : 41
Milliseconds      : 954
Ticks             : 8219544483
TotalDays         : 0.00951336167013889
TotalHours        : 0.228320680083333
TotalMinutes      : 13.699240805
TotalSeconds      : 821.9544483
TotalMilliseconds : 821954.4483

A little over 13 and a half minutes. Doesn’t seem all that bad, but how long does it take to run with the older cmdlets? Lets quickly edit this to use the old school get-mailbox and get-mailboxstatistics

$mailboxes = get-mailbox -Resultsize unlimited
 
foreach ($mailbox in $mailboxes) {
     
    $MxboxStats = $mailbox | get-mailboxstatistics
 
    if ($mailbox.ArchiveStatus -eq "Active" ) {
        $ArchiveMxboxStats = $mailbox | get-mailboxstatistics -Archive
    }
    else {
        $ArchiveMxboxStats = $null
    }
    $properties = [ordered]@{
        DisplayName          = $mailbox.DisplayName
        PrimarySMTPAddress   = $mailbox.PrimarySMTPAddress
        UserPrincipalName    = $mailbox.UserPrincipalName
        Alias                = $mailbox.EmailAddresses
        RecipientTypeDetails = $mailbox.RecipientTypeDetails
        ItemCount            = $MxboxStats.ItemCount
        totalitemsize        = $MxboxStats.totalitemsize
        ArchiveItemCount     = $ArchiveMxboxStats.ItemCount
        ArchiveTotalItemSize = $ArchiveMxboxStats.totalitemsize
    }  
    $out = new-Object -Type PSCustomObject -Property $properties
    Write-Output $out
}

And what do we get for our run time?

PS C:\> measure-command {.\get-mailboxdataold.ps1}


Days              : 0
Hours             : 0
Minutes           : 5
Seconds           : 9
Milliseconds      : 436
Ticks             : 3094362711
TotalDays         : 0.00358143832291667
TotalHours        : 0.08595451975
TotalMinutes      : 5.157271185
TotalSeconds      : 309.4362711
TotalMilliseconds : 309436.2711

5 Minutes and 9 seconds… well damn. Back to the drawing board then?

So it doesn’t look like we’re getting a true performance boost from running the new cmdlets. At least not in scripting. We do get some benefit in readability when using the cli since Microsoft has reduced the default number of properties in the output object. However that isn’t enough of a reason to re-write all of your scripts just yet. In it’s defense this module is still in Beta, and is very much in development. So it may improve over time.

While the new cmdlets aren’t quite ready for prime-time, IMO the module is. This new module is easier to install and maintain than all of the other options out there right now. I currently only use it because it still has access to the legacy Exchange cmdlets, and I can update it with Update-Module. So while Microsoft works out the kinks in the new commands, just use the module to connect to O365 and run all of your old scripts.