Search code examples
xmlpowershellcsvprependfileinfo

Powershell: Add path, filename, filesize and filedate when converting xml to csv


I'm new to scripting; trying to create a powershell script that will read XMLs and create a CSV based on their content.

The directory structure is as follows:
c:\path\to\files

Inside there are 2 folders:
FolderA
FolderB
Inside each of the above there are several subfolders, each with one or more XML files.
Each XML file in turn can have 1 or more "records".

I have the following so far:

Get-ChildItem 'C:\path\to\files\*.xml' -Recurse | ForEach-Object {
  [xml]$xml = Get-Content $_.FullName
  $xml.SelectNodes('//File') |
    Select-Object
} | Export-Csv 'C:\path\to\files\processed.csv' -NoType -Delimiter ';'

This works and creates a CSV file with the contents of all XML files.
What I'd like to do now is have the script above prepend the following information for each file:
path (ie. c:\path\to\files\FolderA\Subfolder1)
file name (ie. File1.xml)
file size (ie. 64 bytes)
file date (ie. Created on 1/1/2018)

These should be the first data in the csv, followed by the XML data; something like:

"path";"filename";"filesize";"filedate";"xmlroot";"xmlchild";"xmlsubchild"

As stated before, the xmlroot,xmlchild,xmlsubchild I already have with my current script, I just need the script to prepend the file information.
If this is not possible with the current script, I'll gladly accept other suggestions :)

Thanks in advance.


Solution

  • Use a set of calculated properties when grabbing the nodes with Select-Object:

    Get-ChildItem 'C:\path\to\files\*.xml' -Recurse | ForEach-Object {
      $file = $_
      [xml]$xml = Get-Content $file.FullName
      $xml.SelectNodes('//File') |
        Select-Object @{Name='path';Expression={$file.FullName}},@{Name='filename';Expression={$file.Name}},@{Name='filesize';Expression={$file.Length}},@{Name='filedate';Expression={$_.CreationTime}},*
    } | Export-Csv 'C:\path\to\files\processed.csv' -NoType -Delimiter ';'