namfon pooksook namfon pooksook - 3 months ago 18
PowerShell Question

Create CSV file in each subdirectory of target directory

I have folder with files as below:

D:\TESzz\Background\BG_Flash-Zootopia-HD-Desktop-Wallpapers.jpg
D:\TESzz\Background\BG_NimmHBD.jpg
D:\TESzz\Background\BG_Note5.jpg
D:\TESzz\Icons\150x150.jpg
D:\TESzz\Icons\Bathroom-gender-sign.png
D:\TESzz\Icons\brocoli.png
D:\TESzz\Icons\Carrot_Clipart_PNG_Image.png
D:\TESzz\Icons\File.txt
D:\TESzz\Icons\garlic.png
D:\TESzz\Icons\ICONS.txt
D:\TESzz\Icons\NoppNimm-1.jpg
D:\TESzz\Icons\NoppNimmIcon.jpg
D:\TESzz\Icons\NoppNimmIcon.png
D:\TESzz\Icons\NoppProfie.jpg
D:\TESzz\Icons\NoppProfileSerious.jpg
D:\TESzz\Icons\pork.png
D:\TESzz\Icons\Profile.jpg
D:\TESzz\Icons\Questionmark.png
D:\TESzz\Icons\sugar.png
D:\TESzz\Icons\Tree.png
D:\TESzz\Icons\wheel.png


I want to export list of file to each sub-folder under "D:\TeSzz" as below

D:\TESzz\Icons\Icons.csv
D:\TESzz\Background\Background.csv


I have my code as below. but it will create "FileList.csv" instead of "Icons.csv" or "Background.csv". :(

Get-ChildItem -path "D:\TESzz\" -directory | ForEach-Object {Get-ChildItem -file "$($_.fullname)" | Export-Csv "$(Join-path $_.fullname 'FileList.csv')"}


Could someone help me on this please?

Answer

I would introduce a variable for the current directory. You don't get your expected result because you are naming the output always as FileList.csv.

Get-ChildItem -path "D:\TESzz\" -directory | 
  ForEach-Object {
    $directory = $_
    Get-ChildItem -file $directory.FullName | 
        Export-Csv (Join-path $directory.FullName "$($directory.BaseName).csv") -Force
}

In the above, notice that where you had FileList, that's now $($directory.BaseName), and therefore different for each directory.