1. 程式人生 > 其它 >win10列出某資料夾下檔案和資料夾大小

win10列出某資料夾下檔案和資料夾大小

採用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:若目錄名有空格需加單引號。如圖:

結果:文章開頭效果展示。