Windows PowerShell

Guy recommends:
Free config generator

Solarwinds Config Generator

This CG will put you in charge of controlling changes to network routers and other SNMP devices.

Download your free Config Generator



PowerShell Scripting  -Recurse

Introduction to PowerShell Scripting -Recurse

When you want a PowerShell command to search sub-directories -recurse is a life saver.  In other contexts this concept is called iteration, or sub-directory recursion.  The cmdlet which benefits most from the -recurse parameter is Get-Childitem.

Topics for PowerShell -Recurse Parameter

 ♣

Example 1 Get-ChildItem -recurse

Our mission is to list all the Windows files under the Program Files folder.  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.  What I should have done was take my own advice and build up gradually like this:-

Stage 1 Problem: The script lists files only in the top level directory.

# PowerShell With Just Get-ChildItem (no recurse)
Clear-Host
Get-ChildItem -path "C:\Program Files\"

Note 1: 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.

Stage 2 Solution: -Recurse drills down and finds lots more files.

# PowerShell -recurse parameter
Clear-Host
Get-ChildItem -path "C:\Program Files\" -recurse

Note 2:  The key to -recurse is the position, it has to be directly after the directory.  In this example I have explicitly used -path to define the location.

Stage 3a Precise Solution:  -Recurse with a filter and wildcard* on the directory name.

# PowerShell -recurse parameter
Clear-Host
$Directory = "C:\Program Files\Windows*"
Get-ChildItem -path $Directory -recurse

Note 3: I wanted to highlight the path be assigning it to a variable, and thus make it easier for you to change the path to suit your task.

Stage 3b Filter for Executables

# PowerShell -recurse parameter
Clear-Host
$Directory = "C:\Program Files\Windows*"
Get-ChildItem -path $Directory -recurse -include *.exe

Stage 3c  Neatly Sorted

# PowerShell -recurse parameter
Clear-Host
$Directory = "C:\Program Files\Windows*"
Get-ChildItem -path $Directory -recurse -include *.exe `
| Sort-Object Name | Format-Table Name, Fullname -auto

Guy Recommends:  A Free Trial of the Orion Network Performance Monitor (NPM) v10Review of Orion NPM v10

Solarwinds' Orion performance monitor will help you discover what's happening on your network.  Also this utility will guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.  Because it produces network-centric views, the NPM is intuitive to navigate, and you can export the results to Microsoft Visio.

Perhaps Orion's best feature is the way it suggests solutions.  Moreover, if problems arise out of the blue, then you can configure Orion NPM v10 to notify members of your team what's changed and how to fix it.

If you are interested in troubleshooting, and creating network maps, then I recommend that you take advantage of Solarwinds' offer and download a free trial of Orion's Network Performance Monitor.

Example 2 Searching The Registry with -recurse

In addition to the file system, Get-ChildItem can work with the registry

# PowerShell Script To Search The Registry
Clear-Host
$Path = "HKLM:\Software\Microsoft\PowerShell"
Get-ChildItem $Path -recurse

Example 3 More Complex Example

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
Clear-Host
$Path = "C:\Windows\System32"
Get-Childitem $Path -recurse | where {$_.Extension -match "exe"}`
 | ft -group {$_.Path} Directory, Name -autosize

Note 4:  You can improve this script by adding -ErrorAction to skip the error message on protected or in use executables.

# PowerShell script to find executables in the Windows\System32 folder
Clear-Host
$Path = "C:\Windows\System32"
Get-Childitem $Path -recurse -errorAction SilentlyContinue |`
where {$_.Extension -match "exe"} | ft -group {$_.Path} Directory, Name -auto

See how to add -ErrorAction SilentlyContinue if you get problems.

Guy Recommends:  A Free Trial of the Orion Network Configuration Monitor (NCM) v6Review of Orion NCM v6

Config management of routers, switches and firewalls is fun with NCM (Network Configuration Manager.  Furthermore, it can help to achieve your compliance policy, for example, pinpoint devices not backed up and discover access infringements or even weak passwords.  This Solarwinds NCM suite can not only detect violations, but also upload scripts to correct the problem.

Most computer problems arise from configuration changes.  Thus it makes sense to get a proper monitoring system so that you can double-check that that all the settings confirm to your security policy.

Download your free trial of Orion's Network Configuration Monitor.

Troubleshooting PowerShell -recurse

The problem with the -recurse parameter is that it only works where the object has leaf items, for example:
C: \Windows\  -recurse.  My point is, I was caught out by trying C: \Windows\*.dll -recurse.

To see my point try these two examples:

# PowerShell recurse finds executables under the Windows folder
Clear-Host
$Path = "C:\Windows\*.exe"
$WinExe = Get-ChildItem $Path -recurse
$WinExe.count

Note 5:  The answer was only about 17.  This script lists .exe files only in the actual Windows folder.  -recurse is useless here.

# PowerShell script to find ALL executables under Windows folder
Write-Host "Waiting for -recurse ..."
$Path = "C:\Windows\"
$WinExe = Get-Childitem $Path -recurse -errorAction SilentlyContinue `
| Where-Object {$_.Extension -match "exe"}
Clear-Host
$WinExe.count

Note 6:  Expected answer over 2,000.  -recurse does its job.  'Where-Object' plays its role in filtering.  Alternatively, you could employ the -include parameter.

Scope of the -recurse Parameter

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: Find PowerShell -recurse Cmdlets

Clear-Host
Get-Command -CommandType cmdlet `
| where { $_.parameters.keys -contains "recurse"}

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, to see more about -recurse you need:

Clear-Host
Get-Help Get-Childitem

Guy Recommends: SolarWinds Engineer's Toolset v10Engineer's Toolset v10

The Engineer's Toolset v10 provides a comprehensive console of utilities for troubleshooting computer problems.  Guy says it helps me monitor what's occurring on the network, and the tools teach me more about how the system itself operates.

There are so many good gadgets, it's like having free rein of a sweetshop. Thankfully the utilities are displayed logically: monitoring, discovery, diagnostic, and Cisco tools.  Download your copy of the Engineer's Toolset v 10

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.

# PowerShell -recurse example
Clear-Host
$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

Clear-Host
$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 7:  When we add -include *.txt the cmdlet works as initially planned.  Actually, you could swap the famous *.* for *.txt, thus : -include *.*

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

Note 9: -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 the above example by removing at least two of the variables, especially on a production script.  The only reason that I employed $Path and $StringText is that when I am creating a script I like to isolate and control each step of the way.

$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 PowerShell -Recurse

-Recurse is a classic switch, which instructs PowerShell commands such as Get-ChildItem to repeat in sub directories.  Once you remember that -recurse comes directly after the directory, then it will serve you well in scripts that need to drill down to find information.

See more PowerShell examples

PowerShell Home   • Syntax  • Get-Credential   • Foreach loops   • Variables   • -whatIf  • -ErrorAction

PowerShell Functions   • [System.Math]   • Windows 7 PowerShell 2.0   • PowerShell 2.0 New features

Please write in if you have a better example script.  Also please report any factual mistakes, grammatical errors or broken links, I will be happy to  correct the fault.

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

WebThis Site

Guy Recommends: WMI Monitor and Its Free!Solarwinds WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.

 Fortunately, Solarwinds have created the WMI Monitor so that you can examine these gems of performance information for free.  Take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

 

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

Please report a broken link, or an error.