welcome to my new weekly feature: powershell rangers. i’ve recently discovered the joys of powershell and i’m rather eager to extol its virtues. something i never thought i would ever do for a microsoft product (asides logparser).

i’m using a source code plugin (syntax highlighter) to format code, so if you see any code you’d like to copy and paste into your own editor hover your cursor over the top right side of the code sample and you should see the universal icon for “copy”.

i needed to recursively search directory for a specific xml file (stored within each sub directory). i was looking to extract an error string nestled within this xml file.

here’s what the structure of the error.xml

<item>
    <level2>
        <level3>
            <errorcode>wibble wibble</errorcode>
        </level3>
    </level2>
</item>

useful things i learnt whilst writing the script below:

how to recurse directories, but only build a file list of directories that contain said xml file.

namespace collisions between powershell’s own item property and an xml file that has a node item called “item”. try loading the sample xml file about peek at it with get-members. you’ll get an error “item” already defined.

bit of a pain, but powershell seems to sort itself out of you know the path to the node you want. alternatively if you need ‘gm’ it use $xml.item | gm

you can test for the existence of an xml node like you can to see if a variable is defined!

$dirBase = "\\elvis-liv\e$\failed"
$dirList = dir -recurse $dirBase | where-object { $_.name -match "ERROR.XML" } | select fullname,directoryname 

foreach( $file in $dirList )
{
        $xml = 1 (gc $file.Fullname)         

        if ($xml.item.level2.level3.errorcode)
        {
                write-host $file.DirectoryName
                write-host "        "$xml.item.level2.level3.errorcode
                write-host ----
        }
}
Tagged with:
 

One Response to powershell rangers: recursively search a directory looking for a specific xml node within a file

  1. RT @booyaa: New Blog Post: recursively search a dir looking 4 a specific xml node w/in a file http://ow.ly/16K4Sj