fbpx

How To Build PowerShell Script for Speed? With 1 Easy Example

Anyone working on IT infrastructure needs to have PowerShell in their toolkit. PowerShell Script become more reliant on your IT infrastructure as it grows, and as a result, they need to run faster.

PowerShell Script

When performing performance testing, it is essential to be able to test and retest your code consistently and obtain results that are comparable from test to test. With the help of the Measure-Command cmdlet in PowerShell script, you can run a PowerShell Script block and determine how long it took to complete.

How To Measure PowerShell Speed?

To measure the speed of the PowerShell script or commands, you can use the Measure-Command cmdlet. This cmdlet allows you to measure the execution time of a specific block of PowerShell code. Here’s how you can use it:

Open PowerShell: Launch the PowerShell console or terminal on your computer.

Write your PowerShell script or command: Type or paste the PowerShell code you want to measure the speed of.

Wrap the code in the Measure-Command cmdlet: Surround your code with the Measure-Command cmdlet as follows:

Measure-Command {
    # Your PowerShell code goes here
}
Execute the code: Press Enter to execute the code block within the Measure-Command cmdlet.
    # Your PowerShell code goes here

View the execution time: The Measure-Command cmdlet will display the execution time, including the TotalMilliseconds, TotalSeconds, and other properties. Look for the TotalMilliseconds property, which represents the total execution time in milliseconds.

Here’s an example to demonstrate the usage:

Measure-Command {
    # Example PowerShell code
    Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 10
}
    # Example PowerShell code

After executing the code block, you will see the execution time displayed in the output, including the TotalMilliseconds value.

By measuring the execution time of your PowerShell script or commands, you can analyze their performance and identify any areas that may need optimization.

Foreach-Object vs. Foreach Loops Speed

Although loops are typically employed to iterate through numerous things, they can provide definitive proof of performance issues.

Consider this PowerShell Script block as an illustration. The current number from the input is output along with the product of the previous number after 1000 iterations of the loop. This PowerShell Script example may be readily scaled on any system by altering the number of times the commands are looped.

1..1000 | ForEach-Object {
 if ($Last) { $Last * $_ } 
 $Last = $_
}
1..1000 | ForEach-Object {
 if ($Last) { $Last * $_ } 
 $Last = $_
}

The same code could result in a considerable delay if it is executed hundreds of thousands or millions of times, even though in many circumstances it will be quick enough. Alternatively, you might write the foreach statement like this:

foreach ($Num in 1..10000) { 
 if ($Last) { $Last * $Num } 

 $Last = $Num
}
foreach ($Num in 1..10000) { 

Due to the usage of the foreach statement rather than the ForEach-Object, this code produces the same result.

Depending on exactly what code is in the loop, your results in terms of performance changes will vary, but you should give it a shot and judge for yourself.

There are situations when you can completely remove the loop and just rely on the pipeline to carry out the entire set of commands for even faster execution. Here is some code that uses a foreach statement to cycle over every file in a directory and obtain the file hash for each one.

The Get-ChildItem command outputs details about the files, including the path of the file, when it is executed. The Get-FileHash command can use this directly through the pipeline.

foreach ($File in Get-ChildItem) { 
 Get-FileHash $File
}
$File in Get-ChildItem

This code would be better written in a single pipeline without the loop like follows:

Get-ChildItem | Get-FileHash
Get-ChildItem | Get-FileHash

These two sets of code would both produce the same result, but the latter exhibits a significant performance improvement.

This example using PowerShell Get-ChildItem and Get-FileHash demonstrates why, wherever possible, you should get rid of loops from your code and replace them with the pipeline.

Arrays vs. Lists: PowerShell Speed++

The results of certain codes are frequently collected for subsequent use. Numerous pieces of code floating around the internet commonly use something similar to what is displayed below. 

The identical code from an earlier section is performed in order to output the product of the current and prior integers. The output will also be added to $Array in this situation per the instructions.

$Array = @()
foreach ($Num in 1..10000) {

 if ($Last) { $Array += $Last * $Num } 
 $Last = $Num
}
foreach ($Num in 1..10000)

The output would be saved to $Array to be utilized later or to print all of the results if $Last = $Num was used.

An ArrayList object should be used in place of an array. It uses slightly different syntax. The ArrayList must first be specifically defined with New-Object System.Collections.ArrayList. Additionally, you will require the.Instead of using += as you can with an array, use the Add()method. This revised code block uses an ArrayList rather than a regular array:

$ArrayList = New-Object System.Collections.ArrayList
foreach ($Num in 1..10000) { 

 if ($Last) { $ArrayList.Add($Last * $Num) }
 $Last = $Num
}
$ArrayList = New-Object

A typical array cannot increase the number of objects it contains. PowerShell Script copies the old and new data into a newly created, larger array by using the operator +=. 

This is a rapid approach to add to an array when done a few times, but when done thousands of times, it has a significant negative influence on performance.

As you use more substantial and substantial amounts of data, this performance disparity keeps expanding. The difference in execution time with 100,000 items versus 10,000 items is over 5 minutes versus a fraction of a second. 

The output of the PowerShell Script is being saved to a variable. Although frequently done, saving the output using variables is not always necessary. You can see a minor advantage over saving to an ArrayList by forgoing saving the output to a variable.