采用powershell脚本实现对win10某文件夹下文件和文件夹大小的统计。
效果展示:
代码展示:
1 param([string]$c); 2 Function showFileInfo($file) 3 { 5 if(-not $file.PSIsContainer){ 6 $fileInfo = (Get-Item -Path $file.FullName -Force -ErrorAction SilentlyContinue | Measure-Object -property length -sum); 7 $fileSize = showItemSize($fileInfo.sum); 8 write-host $file.FullName ' -- ' $fileSize -fore green; 9 } 10 } 11 12 Function showDirInfo($dir) 13 { 14 if($dir.PSIsContainer){ 15 $dirInfo = (Get-ChildItem -Path $dir.FullName -Force -recurse -ErrorAction SilentlyContinue | Where-Object { -not $_.PSIsContainer } | Measure-Object -property length -sum ); 16 $dirSize = showItemSize($dirInfo.sum); 17 write-host $dir.FullName ' -- ' $dirSize -fore Cyan; 18 } 19 } 20 21 Function showItemSize($itemSize){ 22 if($itemSize / 1GB -lt 1){ 23 $itemSize = "{0:N2} MB" -f ($itemSize / 1MB); 24 } 25 else{ 26 $itemSize = "{0:N2} GB" -f ($itemSize / 1GB); 27 } 28 return $itemSize; 29 } 30 31 if(-not [system.IO.Directory]::Exists($c)){ 32 write-host 'check dir please!'; 33 return; 34 } 35 36 #判断当前用户是否为管理员,若不是则强制使用管理员权限。 37 $winPrincipal = [Security.Principal.WindowsPrincipal]([Security.Principal.WindowsIdentity]::GetCurrent()); 38 $winAdmin = [Security.Principal.WindowsBuiltInRole]::Administrator; 39 if( -not $winPrincipal.IsInRole($winAdmin)) 40 { 41 $transParam = ($MyInvocation.BoundParameters.Keys | foreach{"-{0} '{1}'" -f $_ ,$MyInvocation.BoundParameters[$_]}) -join ' '; 42 $curShPath = (Resolve-Path $MyInvocation.MyCommand.Definition).Path; 43 Start-Process "$psHome\powershell.exe" -ArgumentList "$curShPath $transParam" -verb runas; 44 return; 45 } 46 47 $curPath=$c; 48 write-host 'curPath:'$curPath; 49 $curCount = 0; 50 $curFDS = (Get-ChildItem "$curPath" -Force | Sort-Object); #ps3.0后默认不显示隐藏文件,需使用-Force 51 #$curFDS | ForEach-Object {"{0} {1}" -f $_.Gettype(), $_} #查看每个item的类型,类型可以为文件、文件夹、string... 52 foreach ($item in $curFDS) 53 { 54 $curCount++; 55 if(-not $item.PSIsContainer){ 56 showFileInfo($item) 57 }else { 58 showDirInfo($item) 59 } 60 } 61 write-host 'count: '$curCount
将以上代码封装为一个文件,如文件dups.ps1。将dups.ps1加入环境变量,以便可以在每个命令行都可以快捷使用。
使用方法:
场景①:在待统计大小的文件夹地址栏,键入poweshell后会打开ps命令行,再执行dups -c (pwd)。如图:
PS:(pwd)是当前目录信息。
场景②:开始栏打开windowspowershell命令行后,执行:dups -c 目录名。Ps:若目录名有空格需加单引号。如图:
结果:文章开头效果展示。