Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demonstrates assigning object collection with Array addition versus Direct Assignment
$blah = get-childitem -Path c:\temp -Directory
$AddedTicks = Measure-Command -Expression {
$AddedToArray = @()
foreach ($b in $blah) {
$myOBJ = New-Object System.Object
$myOBJ | Add-Member -Type NoteProperty -Name IsBlah -Value $b.BaseName
$AddedToArray += $myOBJ
}
} | Select-Object Ticks
# Cleanup
Remove-Variable colArray -Force -ErrorAction SilentlyContinue
$AssignedTicks = Measure-Command -Expression {
$AssignedWithForEach = foreach ($b in $blah) {
$myOBJ = New-Object System.Object
$myOBJ | Add-Member -Type NoteProperty -Name IsBlah -Value $b.BaseName
$myOBJ
}
} | Select-Object Ticks
"Adding to array executed in $($AddedTicks.Ticks) ticks and produced a $($AddedToArray.GetType()) with $($AddedToArray.count) elements."
"Assigning via ForEach executed in $($AssignedTicks.Ticks) ticks and produced a $($AssignedWithForEach.GetType()) with $($AssignedWithForEach.count) elements."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.