Powershell Counting Files
Date: 2021-10-21
Language: Powershell
Code Link:
Background
Used this for a minor work project to count and list all files under the first sub-directories under a main directory.Problem
Count all the files under first sub-directories under a main directory (including sub-directories) and then list them. Excluding directories in the count or list.Solution
Provided belowAnswer
$MainDir = "/path_to_dir/MainFolder"
function MainScript {
Write-Output "Start Script"
if ($MainDir -notmatch '/$') {
$MainDir = "$MainDir/"
}
$mainDirs = Get-ChildItem -Path $MainDir -Directory
$fileListResult = New-Object Collections.Generic.List[String]
foreach ($dir in $mainDirs) {
$fileListRaw = Get-ChildItem -Path "$mainDir$dir" -File -Recurse
$fileCount = ($fileListRaw | Measure-Object).Count
Write-Output "Main Directory '$dir' has total files: $fileCount"
foreach ($file in $fileListRaw) {
$fileListResult.Add($file.FullName)
}
}
Write-Output "`nList of files found:"
foreach ($file in $fileListResult) {
Write-Output "$file"
}
Write-Output "End Script"
read-host “Press ENTER to continue...”
}
MainScript