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?
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
}
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.
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.
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.
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.
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 π
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.
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.
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?
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.
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
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.
So I was catching up with last week’s Networking Field Day 18Β and the presentation from Big Switch really caught my attention. The proposed that to make multi-cloud architecture, or micro-segmentation work on-prem we need to stop thinking about VLANs and subnets. We need to consider the concept of a Virtual Private Cloud (VPC) as the base level architecture in networking.
Basically Big Switch is asking us to stop worrying about the fiddly nobs of configuring vlans and EVPN, VXLAN. Let the SDN controller worry about that. Then just think about how you want to segment a service, or a dev team, or a project by a VPC.
The concept of a VPC comes from amazon’s AWS platform. Azure calls them vNETs. It’s just the name given to a network segment, it’s a way of making your network an object you just assign to your VMs in the cloud. Because you don’t have direct access to the underlying hardware you are limited to the VPN abstraction layer in AWS. To setup a simple network you stand up a VPC, assign a subnet to it and then start building VMs in that VPC.
What I like about the VPC approach is security is built into this model. Each VPC is completely segregated from each-other. Even though they sit on shared infrastructure traffic for neighboring VPC are completely invisible even if 2-3 other VPCs connect to the same hardware. It’s an elegant solution to a complex problem.
Big Switch’s idea to bring VPC on-prem is brilliant. It provides a level of flexibility that, to me is unrepresented. You want to pull in a hyper-converged stack and deploy that into your DC? Great give it a VPC. What’s that? hyper-converged is your legacy, and you are moving to containers? Great give the container platform a VPC. You don’t have to build new infrastructure around your new system model, you just give it a new virtual network and segment it off.
We’re really looking at the start of an inflection point in networking. I only hope more vendors catch on to this idea of bringing the cloud to the data center.
Be aware this is by no means a exhaustive list of resources, it’s just my go to, or everyday learning list. I don’t use these resources to help me work day to day. However I find it’s important to always be looking ahead. If you are focusing on staying the expert on what you are doing now, you might miss what’s coming next.
Your Peers!
The most important item on this list is the people around you. I have yet to find someone I’ve worked with that wasn’t willing to talk though a problem or a technology. The only trick we’re always busy. Scheduling the time to do it can be a challenge. Bribe someone into lunch π
Best subscription service available for IT study. You have access to electronic copies of O’Reilly books, Cisco, Microsoft, Packt, Sybex, Pearson. Basically any book that was on your study wish list is there. They also have many video learning libraries.
They have an amazing podcast library, most of them focus on networking. The ones I’d call out are the following:
Datanauts – focuses on data center infrastructure trends and deep dives with industry exports. They’ve touched on topics like cloud automation with Terraform, the impact of NVMe on storage networks, breaking down the limitations of Azure Stack.
Full Stack Journey – Interviews with techs, engineers, etc. that have made the move to SRE/DevOps. What drove the decision, what helped them succeed.
Network Break – a quick look at industry news in the world of networking. With deep cynicism that helps cut though the marketing fluff.
Briefings In Brief – basically 1-2 hour vendor meetings distilled down to 5-10 minutes.
An independently run tech conference. They run “Field Days” throghout the year focusing on a different portion of the tech industry. There’s Networking, Storage, Data, Mobility and Cloud field days. It’s an invite only event, however all of the panels are recorded and broadcast live to the general public. They also upload the events online on YouTube (https://www.youtube.com/c/TechfielddaY)
MORE podcasts! While Packet Pushers focus on industry insight, and high level design choices, vBrownBag is that deep dive
Honorable Mentions
IEFT [Free] – ietf.org
Sometimes you just have to go to the source. IETF sets RFC standards that the industry follows.
Udemy [$10-$15 per course] – udemy.com
Great place to pick up a quick tech course. There’s almost always a sale going on too.
CBT Nuggest [$90/mo] – cbtnuggets.com
Probably my favorite source of training videos, but it’s just too expensive. However it’s totally worth signing up for their slack community. You might even see me in the cisco channel from time to time π