Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell – Gather file content and names recursively and output CSV

I have multiple XML files in different subfolders that I am looking to use Powershell to convert them to CSV and output them using the original file name into a different folder. Example of my code:

$xmlfilepaths = Get-ChildItem -Path "\\path\to\files\" -Recurse | where {$_.Name -like '*.xml'}
foreach ($xmlpath in $xmlfilepaths.FullName)
{
    $xmlcontent = Get-Content -Path $xmlpath
}

This part works, but what I would like to do is output these CSV’s to another folder, and keep the filename of the original XML file as the file name. Example:

\path\to\files\alpha\testing123.xml -> \path\to\output\files\testing123.csv
\path\to\files\bravo\production789.xml -> \path\to\output\files\production789.csv

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My problem is once I am in the ‘foreach’ how do I "pull" the file name from either the $xmlpath or $xmlfilepaths variable and pass it along so that my file name input is the same as my filename output?

>Solution :

The original file name is contained in the Name property of each object stored in $xmlfilepaths.

Renaming your variables to something more accurate might help make it more obvious what to do:

$xmlFiles = Get-ChildItem -Path "\\path\to\files\" -Recurse -File -Filter *.xml

foreach ($xmlFile in $xmlFiles)
{
    $xmlContent = Get-Content -Path $xmlFile.FullName

    # !!!
    # do what you need to do to convert the XML to CSV
    # !!!

    # construct new file name and write output file
    $newFileName = $xmlFile.Name -replace '.xml$','.csv'
    $outputPath = Join-Path '\path\to\output\files' $newFileName
    $xmlContent |Set-Content $outputPath
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading