0

I have a script that parses through an XML file and outputs the text of a specific field to a text file for each XML file within a directory.

I am now trying to have this script exclude a specific sub-directory with no luck.

function xml-convert ($srcdir, $destdir) {
  gci $srcdir -r -Filter *.xml | ? {
    $_.DirectoryName -ne $destdir
  } | ForEach-Object{
    $extract = Get-Content $_.FullName

    $newname = Get-Item $_.FullName | % {$_.BaseName}

    $xml = [xml] $extract

    $xml.PortalAutoTextExport.AutoText.ContentText |
      Out-File -FilePath "$destdir\$newname.txt"
  }
}

When I run just this piece

gci $srcdir -r -Filter *.xml | ? {$_.DirectoryName -ne $destdir}

the file list that is returned does NOT show the excluded directory, nor does it show any of the child items for the excluded directory, which is the intention for the entire script.

I've tried several methods for excluding and all have failed. This is the closest I have come to a working solution.

GreatMagusKyros
  • 75
  • 2
  • 11

1 Answers1

1

DirectoryName will never match .\ Ex:

(dir .\Desktop -File).DirectoryName
C:\Users\frode\Desktop
C:\Users\frode\Desktop
C:\Users\frode\Desktop

You need to convert the relative path to absolute path. Example:

function xml-convert ($srcdir, $destdir) {
    $absolutedest = (Resolve-Path $destdir).Path

    Get-ChildItem -Path $srcdir -Recurse -Filter *.xml | Where-Object {
        $_.DirectoryName -ne $absolutedest
    } | ForEach-Object{
        $extract = Get-Content $_.FullName

        $newname = Get-Item $_.FullName | % {$_.BaseName}

        $xml = [xml] $extract

        $xml.PortalAutoTextExport.AutoText.ContentText |
        Out-File -FilePath "$absolutedest\$newname.txt"
    }
}
Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • The intention here is to have this on a flash drive and to be able to run it against the root of the flash drive while being able to exclude specific directories on the root of the flash drive, making it usable regardless which machine I happen to plug into. – GreatMagusKyros Apr 17 '17 at 20:21
  • There's nothing stopping you from doing this. `xml-convert -destdir .\desktop` is fine, but the script itself needs to convert it to an absolute path to match it with the `DirectoryName`-property. `Resolve-Path` will turn it into whatever letter/path it refers to on your flash drive – Frode F. Apr 17 '17 at 20:22
  • I see now. Thank you, that makes more sense When explained that way! – GreatMagusKyros Apr 17 '17 at 20:28