Tuning Script Performance

by Oct 20, 2021

If a script runs slow, it’s not always obvious what causes the delays, and where to optimize. With a PowerShell module called “PSProfiler” you can test how long each line in a script takes to execute. It runs both in Windows PowerShell and PowerShell 7.

Start by installing the module:

 
PS> Install-Module -Name PSProfiler -Scope CurrentUser  
 

Next, invoke your script with Measure-Script:

 
PS> Measure-Script -Path 'C:\Users\tobias\test123.ps1'  
 

Once your script completes, you get a sophisticated report telling you exactly how often each line of your script was executed, and how long it took:

 
      Count  Line       Time Taken Statement                                                                                            
      -----  ----       ---------- ---------                                                                                            
          1     1    00:00.0033734 $Path = "$env:temp\tv.json"                                                                          
          0     2    00:00.0000000                                                                                                      
          1     3    00:28.1602885 $data = Get-Content -Path $Path -Raw |                                                               
          0     4    00:00.0000000 ConvertFrom-Json |                                                                                   
          1     5    00:26.6558438 ForEach-Object { $_ } |                                                                              
          0     6    00:00.0000000 ForEach-Object {                                                                                     
          0     7    00:00.0000000                                                                                                      
     101000     8    00:01.4408993   $title = '{0,5} [{2}] "{1}" ({3})' -f ([Object[]]$_)                                               
     101000     9    00:13.6815132   $title | Add-Member -MemberType NoteProperty -Name Data -Value $_ -PassThru                        
          0    10    00:00.0000000 }                                                                                                    
          0    11    00:00.0000000                                                                                                      
...
 


Twitter This Tip! ReTweet this Tip!