Windows PowerShell


PowerShell Scripting  -Recurse

Introduction to PowerShell Scripting -Recurse

-Recurse is a life saver for PowerShell commands that wish to search sub-directories.  In other contexts this concept is called iteration, or sub-directory recursion.  A classic usage for -recurse is with get-Childitem.

It was the positioning of -recurse that gave me my biggest headache.  My tactical error was to try and introduce -recurse into a long statement (Example 2).  What I should have done was take my own advice and build up gradually (Example 1).

Topics for -Recurse

Example 1 Simple Recursive behaviour

While this is a simple example and it works, it is not always ideal to output all the files; usually we wish to filter on filename or extension.

To get see the full effect you would create subdirectories under $Path (D:\step) and then observe the output of files in both parent and child directories.

$Path = "D:\Step"
$PathDir = get-Childitem $Path -recurse
$PathDir

Learning Point

Note 1:  The key to -recurse is the position, it has to be directly after the directory, or in this case the $variable holding he value of the directory.  In this example the position is obvious, or easy to find. 

However, in more complex examples it is easy to misplace the -recurse command.  Surprisingly, the script often completed with -recurse in the wrong place, but the output only displayed the top level information.  This robust behaviour made it tricky to pin down true place for the -recurse switch.

Note 2: get-Childitem is the equivalent of dir.  In fact PowerShell creates an alias called dir, thus this old command still works on the command line.

Example 2 Searching recursively for only .exe files

I switched this example to the C:\ windows directory.  Even filtering for just .exe files produced a huge output.

# PowerShell script to find executable in the Windows folder
$Path = "C:\windows"
$wind =get-Childitem $Path -recurse | where{$_.Extension -match "exe"}
$wind

Learning Points

Note 1:  It looks obvious when you see both examples where to position -recurse.  A classic case for building scripts gradually.

Example 3 Complex

I only include this example to explain how difficult it can be to decide where to place -recurse.  When you study that long middle line you can see how it's possible to group the output and select a custom format-Table (ft).

# PowerShell script to find executable in the Windows folder
$Path = "C:\windows"
$wind = get-Childitem $Path -recurse | where{$_.Extension -match "exe"} `
 | ft -group{$_.Path} name, directory -autosize
$wind

Scope of -Recurse

The -recurse parameter works only when the path has a folder that has child items, for example:
C: \Windows\  -recurse.  My point is, I was caught out by trying C: \Windows\*.dll -recurse.

Furthermore, while -recurse works nicely for the above get-Childitem, I emphasise CHILDitem.  I could neither get it to work with get-Item, nor could I see -recurse amongst the parameters for plain get-Item.

Research

To verify the situation with get-Childitem, get-Item and -recurse, try these commands:
get-help get-Childitem -full
Also try:
get-help get-Item -full

Incidentally, get-Childitem | get-Member does not, repeat not, list -recurse.  This is because -recurse is a parameter, or what I call a switch.  get-Member lists methods and properties, but not parameters, for that you need:
get-help get-Childitem.

Problems with -recurse, and how to overcome them

Case Study

The mission is to list all files containing the word 'Microsoft' in the Windows folder or its sub-folders.  For this we use the select-string pattern matching command.

The problem is that this script does not work.  All that happens is that we get an error: Cannot find path... Path does not exist.

$i=0
$Path = "C:\windows"
$Full = get-ChildItem $Path -recurse
$StringText = "Microsoft"
$List = select-string -pattern $StringText $Full
foreach ($file in $List) {$file.Path; $i++}
$i

The solution: Add the -include parameter

$i=0
$Path = "C:\windows"
$Full = get-ChildItem $Path -include *.txt -recurse
$StringText = "Microsoft"
$List = select-string -pattern $StringText $Full
foreach ($file in $List) {$file.Path; $i++}
$i

Note 1: When we add -include *.txt the cmdlet works as initially planned.  Actually, you could swap the famous *.* for *.txt, thus : -include *.*

Note 2: -include only works when you also append the -recurse parameter.

Note 3: -include applies to the filename and extension.  Where I made a mistake was thinking that -include would apply to the path.

Simplification

There is no reason why you cannot simplify by removing at least two of the variables, especially on a production script.  The only reason that I employed $Path and $StringText is that I like to isolate and control each step of the script.

$i=0
$Full = get-ChildItem C:\windows -include *.txt -recurse
$List = select-string -pattern "Microsoft" $Full
foreach ($file in $List) {$file.Path; $i++}
$i

Summary of -Recurse

-Recurse is a classic switch to instruct PowerShell commands to repeat for sub directories.  Once you learn the name -recurse and the position, directly after the directory, then it will serve you well in scripts that need to search repeatedly for information.

See also PowerShell syntax

PowerShell Home   • Syntax   • Loops   • Variables  • What If   • Functions   • Replace

Please write in if you see errors of any kind.  Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.

Download my ebook:Getting Started with PowerShell
Getting Started with PowerShell - only $9.25

You get 36 topics organized into these 3 sections:
   1) Getting Started
   2) Real-life tasks
   3) Examples of Syntax.

In addition to the ebook, you get a PDF version of this  Introduction to PowerShell ebook  It runs to 120 pages of A4.

 *


Google

Webcomputerperformance.co.uk

Guy Recommends: SolarWinds Exchange Monitor

Exchange Monitor from SolarWindsHere is a free tool to monitor your Exchange Server

 

Home Copyright © 1999-2008 Computer Performance LTD All rights reserved

Please report a broken link, or an error.