Powershell

How to Optimize PowerShell Script Performance

PowerShell is a scripting language that is easier to use and understand. It is used for configuring the systems and automating tasks. PowerShell creates .NET objects using a new object cmdlet. Most command-line Shells are based on text; however, PowerShell helps users in working with objects using the .NET framework.

This article will help users optimize the PowerShell script performance including the following content:

How to Optimize PowerShell Script Performance?

PowerShell scripts use the.NET framework. Avoiding pipelines is faster than the PowerShell functions using pipelines and utilizes .NET framework objects only when it is necessary. Pipelining reduces the readability of scripts. Users can optimize scripts to increase script performance.

Optimize Speed by Suppressing Output Using Null

Suppressing Output avoids pipeline that increases the execution speed of scripts. You can use Null(automatic variable) in four different ways to suppress output sent to the console of PowerShell. To do so:

  • Search and open Windows PowerShell as an administrator.
  • Create a new directory using the “mkdir” command:
mkdir newfolder

 

Then, load assemblies in the PowerShell to hold all the functionalities of PowerShell:

[System.Reflection.Assembly]::LoadWithPartialName('system.windows.forms')

 

Method 1: Use of Cmdlet Out-Null

The “Out-Null” cmdlet discards output instead of using it in the pipeline. Here, without using “Out-Null” sample.txt file is displayed on the terminal with its time and date of execution:

New-Item -ItemType File -Name sample.txt

 

Next, use the “Out-Null” command to hide output in the pipeline:

New-Item -ItemType File -Name sample2.txt | Out-Null

 

Method 2: [void] Casting

It will optimize the speed of the script and also suppress compiler warnings:

$Array= New-Object System.Collections.ArrayList
$Array.Add(1)
$Array.Add(2)
$Array.Add(3)
[void]$Array.Add(4)
$Array

 

Method 3: Redirecting File to $null

This will suppress all the comments generated by the execution of any file or command. For that purpose, run the following command without using $null:

$var= New-Object System.Windows.Forms.Form
$var.ShowDialog()

 

Afterward, execute along with the $null variable:

$var.ShowDialog() > $null

 

Method 4: Assigning Output to $null

This will suppress the output of each command. The below-given command, will not display the details about the creation of a new directory:

$null = mkdir dir

 

Optimize Speed In Array Addition

Array addition using += operators is a time-consuming process especially when you are dealing with large data. PowerShell has a fixed size so whenever you add a new element in the array, it will generate a new array with one slot for that newly added element. The result of this operation will take extra time and memory. While Array lists have a .NET developer background to fix the speed issue. Comparison of time taken using += operator and ArrayLists.

In the provided code block, the loop is used to process, generate, and collect results in the Analysis variable:

$result = @()
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()

1..10000 | Foreach-Object {
        $result += "Summing up $_"
}
$Analysis = '{0} elements collected in {1:n1} seconds'
$Analysis -f $result.Count, $stopwatch.Elapsed.TotalSeconds

 

In the output section, it shows that it takes 2.3 seconds to run 10000 elements.

$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
$result = 1..10000 | Foreach-Object {
    "I am adding $_"
}
$Analysis = '{0} elements collected in {1:n1} seconds'
$Analysis -f $result.Count, $stopwatch.Elapsed.TotalSeconds

 

Now, use the ArrayList instead of the += operator in the previously discussed code:

It can be observed that the above-executed code takes 0.1 seconds to collect 10,000, which is a huge increase in speed.

Optimize Speed In String Addition

String addition using the += operator slows down the speed of the program. They are immutable so every time the concatenation of the string is done it will create a new string object which results in memory issues and a slower time of execution. We can resolve this issue using StringBuilder. It is mutable, having a sequence of characters.

In the below-given code, we are using the += operator and iterating loop over 10000:

$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()

$data = ""

1..100000 | Foreach-Object {
    $data += "operating on $_`r`n"
}
$Analysis = 'composed string of length {0} in {1:n1} seconds'
$Analysis -f $data.Length, $stopwatch.Elapsed.TotalSeconds

 

The output displays that it will take 145.0 seconds to compose a string of length 1988895.

Next, use the “StringBuilder” and “Appenline()” to explicitly append the new line:

$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()

$data = [System.Text.StringBuilder]""

1..100000 | Foreach-Object {
    $null = $data.AppendLine("working on $_")
}

#conversion of StringBuilder back in string
$stringText = $data.ToString()

$Analysis = 'composed string of length {0} in {1:n1} seconds'
$Analysis -f $stringText.Length, $stopwatch.Elapsed.TotalSeconds

 

This method takes 0.6 seconds to compose the string of length 1788895. It gives the idea that it is fast for string addition as compared to += operator addition.

Conclusion:

Optimization of script performance is essential for achieving higher efficiency and better performance. Execution time for the scripts can be reduced by suppressing output and speeding up string concatenation and array addition. Output can be suppressed using Null (automatic variable), resulting in efficient execution. You can increase speed by replacing +=operator in string concatenation and arrays with StringBuilders and ArrayList. This guide explained the usage of fewer resources for a significant increase in script execution speed.

About the author

Maria Naz

I hold a master's degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.