Powershell Count List Folders


Date: 2021-10-25
Language: Powershell
Code Link:

Background

Used this for a minor work project to count and list all subfolders (of specified string pattern) under the first sub-directories under a main directory.

Problem

Count all the subfolders under first subfolder under a main folder (including sub-folders) and then list them.

Solution

Provided below
Answer
$MainDir = "[path_to_dir]\[MainFolder]"
$NameToFind = "S\d\d\d\d\d--"
$fileRecord = "koala-is-so-smart"

function MainScript {
    Write-Output "Start Script"
    $today = Get-Date -Format "yyyy-MM-dd"
    Write-Output "Check end of line"
    if ($MainDir -notmatch '/$') {
        $MainDir = "$MainDir/"
    }
    Write-Output "Get subfolders"
    $mainDirs = Get-ChildItem -Path $MainDir -Directory
    $fileListResult = New-Object Collections.Generic.List[String]
    $folderCountList = New-Object Collections.Generic.List[String]
    Write-Output "Loop subfolders"
    foreach ($dir in $mainDirs) {
        $dirName =$dir.Name
        #Write-Output "Matching subfolders in subfolders"
        $subDirs = Get-ChildItem $MainDir\$dirName -Recurse | Where-Object { $_.PSIsContainer -and $_.Name -cmatch $NameToFind}
        #Write-Output "Counting subfolders in subfolders"
        $fileCount = ($subDirs  | Measure-Object).Count
        $countResult = "Folder:`"$dir`"; Total: $fileCount"
        $folderCountList.Add($countResult)
        Write-Output $countResult

        $fileListResult.Add("`nFolder Owner: $dir")
        foreach ($file in $subDirs) {
    
            $fileListResult.Add("Name: $file")
        }
    }
    $fileRecordPath = "$PSScriptRoot\$fileRecord`_$today.txt"
    $folderCountList | Out-File -FilePath "$fileRecordPath"
    $fileListResult | Out-File -FilePath "$fileRecordPath"  -Append

    Write-Output "Saved results to $fileRecord"
    Write-Output "End Script"
    read-host “Press ENTER to exit...”
}

MainScript