<# .SYNOPSIS Quick Hits: Speed Up Some of your Commands by Avoiding the Pipeline .DESCRIPTION Sometimes running a command using the pipeline can take a while depending on the amount of data that is being processed. For the easiest example, I will make use of Get-Random to demonstrate the differences in speed and how much memory is used. .LINK Thanks: https://learn-powershell.net/2013/01/13/quick-hits-speed-up-some-of-your-commands-by-avoiding-the-pipeline/ #> # Breifly introduce the current running script. Write-Host "`n" ($MyInvocation.ScriptName) # Get-Help wont work if script starts with function... Write-Host (Get-Help $PSCommandPath).Synopsis -ForegroundColor DarkGray function Test-RandomPipelineBenchmark { <# .DESCRIPTION Here you see that it takes a little over a minute to run, but the amount of memory used isn’t a whole lot; about 6KB. Instead, you should take a look at using the '–InputObject' parameter as it accepts a collection of objects to use instead for much faster performance. .OUTPUTS Memory Before: 206, 064KB TotalSeconds : 6.2035622 Memory After : 206, 064KB #> ("Memory Before: {0:#,#}KB" -f ((Get-Process -Id $PID).PeakWorkingSet / 1kb)) ("TotalSeconds : {0}" -f (Measure-Command { 1..1E6 | Get-Random }).TotalSeconds) ("Memory After : {0:#,#}KB" -f ((Get-Process -Id $PID).PeakWorkingSet / 1kb)) } function Test-RandomInputObjectBenchmark { <# .DESCRIPTION This didn’t event take a second to run using the InputObject parameter. However, you will see that the amount of memory required to perform this operation jumped up by about 20KB, so caution should be used if trying to run this against a lot of data to avoid running into memory issues. .OUTPUTS Memory Before: 206, 204KB TotalSeconds : 0.36981 Memory After : 238, 912KB #> ("Memory Before: {0:#,#}KB" -f ((Get-Process -Id $PID).PeakWorkingSet / 1kb)) ("TotalSeconds : {0}" -f (Measure-Command { Get-Random -InputObject (1..1E6) }).TotalSeconds) ("Memory After : {0:#,#}KB" -f ((Get-Process -Id $PID).PeakWorkingSet / 1kb)) } # Run the Test-Functions Write-Host "$('-'*80)" -ForegroundColor DarkGray # Seperator Write-Host "Running: Benchmark #1 [Pipeline]" Test-RandomPipelineBenchmark Write-Host "$('-'*80)" -ForegroundColor DarkGray # Seperator Write-Host "Running: Benchmark #1 [InputObject]" Test-RandomInputObjectBenchmark Write-Host "$('-'*80)" -ForegroundColor DarkGray # Seperator