简体   繁体   中英

Windows10/powershell: how to count files and then sort them by subfolders?

I have a script in Linux that searches/counts all the files in subfolders and gives me a count for each.

Sample output when run: my-count-script.sh /usr

 5322 X11R6
  316 bin
   89 lib
 2165 libdata
   50 libexec
19220 local
   10 mdec
  206 sbin
 8970 share

This gives me count for all folders immediately inside /usr . So the actual path to share is /usr/share . path to bin is /usr/bin .

I guess /usr is the parent and the children includes share , bin and etc. I want the display to stop at the "children" level.

Any ideas how it can be done in power shell?

像这样的快速班轮:

(ls c:\YourPath\*\* -File).Directory | Group-Object name

You want something like:

Get-Childitem $home -recurse | Group-Object Directory -noelement

I have used $home as a directory spec here, but you will probably want to use one that's more relevant to your situation.

This will get child item count for each sub directory on its first level.

Gets all children that are directories then for each directory it gets all files recursively for each sub folder.

Get-childitem C:\Test -Recurse -Depth 0 -Directory | %{@{$_.Name = (Get-ChildItem $_.FullName -File -Recurse).count}} | format-table

If you do not want the recursive count then run this which will just get you the file count in each sub directory

Get-childitem C:\Test -Recurse -Depth 0 -Directory | %{@{$_.Name = (Get-ChildItem $_.FullName -File).count}} | format-table

Here is a function to also achieve what you would like

function Get-SubDirectoryCount(){
    Param(
      [Parameter(Mandatory=$True)]
      [string]$Directory,
      [switch]$Recurse,
      [Parameter(ParameterSetName='FilesOnly')]
      [switch]$FilesOnly,
      [Parameter(ParameterSetName='DirectoriesOnly')]
      [switch]$DirectoriesOnly,
      [Parameter(ParameterSetName='FilesDirectoriesOnly')]
      [switch]$FilesAndDirectories
    )
    Invoke-expression  "Get-childitem $Directory -Recurse -Depth 0 -Directory | %{@{`$_.Name = (Get-ChildItem `$_.FullName $(if($DirectoriesOnly){write-output "-Directory"})$(if($FilesOnly){write-output "-File"}) $(if($Recurse){write-output "-Recurse"})).count}} | format-table"
}

#Get Files and Directories Recursively 
Get-SubDirectoryCount -Directory C:\Test -FilesAndDirectories -Recurse
#Get Files Recursively 
Get-SubDirectoryCount -Directory C:\Test -FilesOnly -Recurse
#Get Directories Recursively
Get-SubDirectoryCount -Directory C:\Test -DirectoriesOnly -Recurse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM