I am trying to count all files in subfolder and extract to csv. Here is the file structure.
C:\TEST\FolderAAA
|-folderA1
|-folderA1.1
|-file
|-file
|-folderA1.2
|-file
|-file
|-folderA1.3
|-file
|-file
|-folderA2
|-folderA1.1
|-file
|-file
|-folderA2.2
|-file
|-file
|-folderA2.3
|-file
|-file
C:\TEST\FolderBBB
|-folderB1
|-folderB1.1
|-file
|-file
|-folderB1.2
|-file
|-file
|-folderB1.3
|-file
|-file
|-folderB2
|-folderB2.1
|-file
|-file
|-folderB2.2
|-file
|-file
|-folderB3.3
|-file
|-file
C:\TEST\FolderCCC
|-folderC1
|-folderC1.1
|-file
|-file
|-folderC1.2
|-file
|-file
|-folderC1.3
|-file
|-file
|-folderC2
|-folderC2.1
|-file
|-file
|-folderC2.2
|-file
|-file
|-folderC3.3
|-file
|-file
I am looking for a CSV output with the below format:
Column A Column B Folders File Count ---------------------------- FolderAAA 0 folderA1 0 folderA1.1 2 folderA1.2 2 folderA1.3 2 folderA2 0 folderA2.1 2 folderA2.2 2 folderA2.3 2 Space/New Blank Row -------- FolderBBB 0 folderB1 0 folderB1.1 2 folderB1.2 2 folderB1.3 2 folderB2 0 folderB2.1 2 folderB2.2 2 folderB2.3 2 Space/New Blank Row -------- FolderCCC 0 folderC1 0 folderC1.1 2 folderC1.2 2 folderC1.3 2 folderC2 0 folderC2.1 2 folderC2.2 2 folderC2.3 2
I tried and modified this code that I found after doing some research here:
$FOLDER_ROOT = "C:\TEST\"
$OUTPUT_LOCATION = "C:\TEST\RESULT\Folder_Count.txt"
$OUTPUT_CSV = "C:\TEST\RESULT\Folder_Count.csv"
function DirX($directory) {
Remove-Item $OUTPUT_LOCATION
foreach ($singleDirectory in (Get-ChildItem $directory -Recurse -Directory)) {
$count = Get-ChildItem $singleDirectory.FullName -File |
Measure-Object |
%{$_.Count}
$summary = $singleDirectory.Basename + " - " + $count
Add-Content $OUTPUT_LOCATION $summary
}
}
DirX($FOLDER_ROOT)
Import-Csv $OUTPUT_LOCATION -Delimiter "-" -Header Folder, Count |
Export-Csv $OUTPUT_CSV -NoTypeInformation
The extract I am getting does not format according to what I am trying to achieve.
Currently the extract is formatted incorrectly this way:
Column A Column B Folders File Count ---------------------------- FolderAAA 0 folderA1 0 folderA2 0 folderA1.1 2 folderA1.2 2 folderA1.3 2 folderA2.1 2 folderA2.2 2 folderA2.3 2
Get-ChildItem -Recurse -Directorytraverses the directory structure using breadth first search. This is the root cause of why the output shows up in the order AAA -> A1, A2 -> etc.. One solution is to perform the traversal yourself by implementing a depth first traversal algorithm."depth first" + "traversal" + "directories" -graphon google?