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 its about 100x faster, too.

Note that you can assign anything to a variablewhether its 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."

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.

Get your poster here!

Related links