Book Image

PowerShell Troubleshooting Guide

By : Mike Shepard
Book Image

PowerShell Troubleshooting Guide

By: Mike Shepard

Overview of this book

Table of Contents (15 chapters)
PowerShell Troubleshooting Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Sequences of assignment statements


As I have mentioned several times, scripting in PowerShell is somewhat different than programming in other languages. A programmer who isn't comfortable with the pipeline might easily fall into the trap of writing code in a style that matches the imperative programming language that he is most familiar with. For instance, filtering and sorting a list of files in a directory could easily be seen as a sequence of operations, as follows:

  1. Get the list of files.

  2. Filter the list of files to match the given criteria.

  3. Sort the remaining list of files.

This thought process could lead to a PowerShell script that looks like this:

function get-sortedFilteredList{
Param($folder,$extension)

    $files = dir $folder
    $matchingFiles = where-object -InputObject $files -FilterScript {$_.Extension -eq $extension}
    $sortedMatches = sort-object -InputObject $matchingFiles -Property Name

    return $sortedMatches
}

While this is a correct solution to the problem in some senses...