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

         

 

         

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM