Search code examples
arraysxmlfilepowershellmsxml

Name files with values from array


I want to name files with values stored in an array.

I have a folder with some .xml files in. I have processed the files with MSXSL, and have written the output files to an output folder.

I want to name the output files with the same name as the original files. However at the moment my script is calling the files [0].xml, [1].xml, [2].xml, etc.

Here is my script so far:

[array]$files = Get-ChildItem c:\powershell\ -Filter *.xml    
[array]$names = Get-ChildItem c:\powershell\ -Filter *.xml | Select-Object Name

$current = 0

foreach ($file in $files) {
    c:\powershell\msxsl.exe $files[$current] transform.xslt -o c:\powershell\output\$names[$current].xml
    $current ++
}

I am obviously messing up the main line of my for loop.

MSXSL.EXE takes the -o switch, which names the output file. I have tried to reference elements of my $names array but it isn't working.


Solution

  • There's no reason to maintain 2 arrays, nor incrementing the counter manually.

    For the orignal file path, use the FullName property, and for the name alone, use Name:

    $files = Get-ChildItem c:\powershell\ -Filter *.xml    
    
    foreach ($file in $files) {
        c:\powershell\msxsl.exe $file.FullName transform.xslt -o $(Join-Path 'c:\powershell\output' $file.Name)
    }