Powershell Count List Find Folder
Date: 2021-11-09
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 a main folder (including sub-folders) and then list them.Solution
Provided belowAnswer
$MainDir = "\path_to_folder\MainFolder"
$NameToFind = "S\d\d\d\d\d"
$initialList = 'EQ', 'kk', 'pp'
$fileRecord = "she-is-so-smart"
function MainScript {
Write-Output "Start Script"
$today = Get-Date -Format "yyyy-MM-dd"
if ($MainDir -notmatch '/$') {
$MainDir = "$MainDir/"
}
$mainDirs = Get-ChildItem -Path $MainDir -Directory
$fileListResult = New-Object Collections.Generic.List[String]
$folderCountList = New-Object Collections.Generic.List[String]
foreach ($initial in $initialList) {
$subDirsName = Get-ChildItem "C:\Users\S\Documents\MainFolder" -Recurse | Where-Object { ($_.Name -match "$NameToFind.*$initial$")}
$nameFolders = $subDirsName.Parent
$nameCount = ($subDirsName | Measure).Count
$countResult = "User: $initial, has: $nameCount folders done."
Write-Output $countResult
$folderCountList.Add($countResult)
$fileListResult.Add("`nFolders done by: $initial")
foreach ($file in $subDirsName) {
$fullName = $file.FullName
$fileListResult.Add("Name: $fullName")
}
}
$fileRecordName = "$fileRecord`_$today.txt"
$fileRecordPath = "$PSScriptRoot\$fileRecordName"
$folderCountList | Out-File -FilePath "$fileRecordPath"
$fileListResult | Out-File -FilePath "$fileRecordPath" -Append
Write-Output "Saved results to $fileRecordName"
Write-Output "End Script"
read-host “Press ENTER to exit...”
}
MainScript