Skip to the main content.

Unlocking the Power of PowerShell: Tips for Success

Assign results correctly: Better performance, cleaner code

Tired of cumbersome PowerShell scripts? Learn how direct assignment of variables can simplify your code and significantly increase performance.

When you need to store the results of a command, you naturally assign it to a variable:


$result = Get-Process 

 

However, when you need to store results produced by a loop, many users resort to manual array handling:


# starting with an empty array $result = @()


$list = 'Tobias',' Chrissy', 'Alex', 'Melinda', 'Jordan', 'Jeffrey'
foreach ($element in $list)
{
# manually putting results into array
$result += "processing $element"
}
$result.count
$result 

 

Why not simply assign the result to a variable again and let PowerShell take care of all the array handling?


$list = 'Tobias',' Chrissy', 'Alex', 'Melinda', 'Jordan', 'Jeffrey'
$result = foreach ($element in $list)
{
# not assigning information turns it into a return value
"processing $element"
}

$result.count
$result

 

This is much easier, and it’s about 100x faster, too.

Note that you can assign anything to a variable—whether it’s a command, a control structure such as a loop, or even a condition. Most people write like this:


$date = Get-Date

if ($date.Hour -lt 12) 
{
    $text = 'morning'
}
else
{
    $text = 'evening'
}

"It is $text."

 

Why not assign the result to a variable just once and take it directly from the control structure:


$date = Get-Date

$text = 
if ($date.Hour -lt 12) 
{
    'morning'
}
else
{
    'evening'
}

"It is $text." 

 

 

 

 

Good2know

Your ultimate PowerShell Cheat Sheet

Unleash the full potential of PowerShell with our handy poster. Whether you're a beginner or a seasoned pro, this cheat sheet is designed to be your go-to resource for the most important and commonly used cmdlets.

The poster is available for download and in paper form.

PowerShell Poster 2023

Get your poster here!

 

 

Related links 

 

Related posts

4 min read

Bulk Testing PowerShell Scripts with the Tokenizer

In Part 1, we explored the internal PowerShell parser to see how it analyzes code and breaks it down into individual...

3 min read

Mastering PowerShell Tokenization for Efficient Scripting

The internal PowerShell parser processes any code before execution. With full access to this parser, you can analyze...

3 min read

Using .NET Libraries in PowerShell - Functions, Cmdlets and .NET

In part 3, we identified a useful .NET method to display system dialogs and then wrapped it inside a new PowerShell...

About the author: