Create CSV file in each subdirectory of target directory

孤街醉人 提交于 2021-01-27 15:08:36

问题


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?


回答1:


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.




回答2:


You can put the parent directory name in a variable, then use it to form the output file name:

$parentDir = "D:\TESzz";
Get-ChildItem -path $parentDir -directory | ForEach-Object {Get-ChildItem -name $parentDir\$_ | Export-Csv -path $(Join-path $parentDir\$_ ($_.Name+'.csv'))}

Here, we use $parentDir to create the export path.



来源:https://stackoverflow.com/questions/39160105/create-csv-file-in-each-subdirectory-of-target-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!