Home > Mobile >  Powershell - Gather file content and names recursively and output CSV
Powershell - Gather file content and names recursively and output CSV

Time:12-20

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

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?

CodePudding user response:

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
}

CodePudding user response:

To get new filename use following :

$filename = "\path\to\files\alpha\testing123.xml"
$basename = $filename.Substring($Filename.LastIndexOf("\")   1)
$basename = $basename.SubString(0, $basename.LastIndexOf("."))
Write-Host $basename
$newName = "\path\to\output\files\"   $basename   ".csv"
Write-Host $newname
  • Related