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

Understanding PowerShell Arrays

PowerShell arrays are a powerful and versatile way of managing collections of data, enabling you to efficiently...

5 min read

Enhance PowerShell scripts to validate and transform data

Tired of hidden errors in your PowerShell scripts? Discover how validation and transformation attributes can bring...

4 min read

Embrace the PowerShell pipeline

Want to make your PowerShell scripts faster and more flexible? Learn how to optimize the pipeline with script blocks...

About the author: