2015-02-06 32 views
1

參考my previous post,我需要一個腳本來算的數目:名稱中 當只有1個文件匹配時,計算dir中的文件數目會返回0嗎?

的例子目錄結構將某些字符串

  • 標準的文本文件
  • TEXTFILES像這樣:

    ROOT 
        BAR001 
         foo_1.txt 
         foo_2.txt 
         foo_ignore_this_1.txt 
        BAR001_a 
         foo_3.txt 
         foo_4.txt 
         foo_ignore_this_2.txt 
         foo_ignore_this_3.txt 
        BAR001_b 
         foo_5.txt 
         foo_ignore_this_4.txt 
        BAR002 
         baz_1.txt 
         baz_ignore_this_1.txt 
        BAR002_a 
         baz_2.txt 
         baz_ignore_this_2.txt 
        BAR002_b 
         baz_3.txt 
         baz_4.txt 
         baz_5.txt 
         baz_ignore_this_3.txt 
        BAR002_c 
         baz_ignore_this_4.txt 
        BAR003 
         lor_1.txt 
    

    結構將永遠是這樣的,所以沒有更深的子文件夾。因爲我只能使用PS 2,我現在有:

    Function Filecount { 
        param 
        (
         [string]$dir 
        ) 
    
        Get-ChildItem -Path $dir | Where {$_.PSIsContainer} | Sort-Object -Property Name | ForEach-Object { 
         $Properties = @{ 
          "Last Modified" = $_.LastWriteTime 
          "Folder Name" = $_.Name; 
          Originals  = [int](Get-ChildItem -Recurse -Exclude "*_ignore_this_*" -Path $_.FullName).count 
          Ignored = [int](Get-ChildItem -Recurse -Include "*_ignore_this_*" -Path $_.FullName).count 
         } 
         New-Object PSObject -Property $Properties 
        } 
    } 
    

    輸出是這樣的(最後修改未填寫):

    Folder Name  Last Modified Originals Ignored 
    -----------  ------------- --------- ------- 
    BAR001         2   1 
    BAR001_a         2   2 
    BAR001_b         0   0 <------- ?? 
    BAR002         0   0 <------- ?? 
    BAR002_a         0   0 <------- ?? 
    BAR002_b         3   1 
    

    的問題是該每當有1文本文件和1「忽略」文本文件在目錄中,該腳本列出兩個列而不是1.我不知道爲什麼。你做?

回答

2

你需要從Get-ChildItem數組的回報,所以這將有哪怕它只返回1個對象.count屬性:

Function Filecount { 
    param 
    (
     [string]$dir 
    ) 

    Get-ChildItem -Path $dir | Where {$_.PSIsContainer} | Sort-Object -Property Name | ForEach-Object { 
     $Properties = @{ 
      "Last Modified" = $_.LastWriteTime 
      "Folder Name" = $_.Name; 
      Originals  = @(Get-ChildItem -Recurse -Exclude "*_ignore_this_*" -Path $_.FullName).count 
      Ignored   = @(Get-ChildItem -Recurse -Include "*_ignore_this_*" -Path $_.FullName).count 
     } 
     New-Object PSObject -Property $Properties 
    } 
} 
+0

偉大的作品,但我不明白爲什麼。在我的版本中,我使用'cgi'對一個文件夾中的文件數進行了計數,並將結果作爲數字進行投射。我同意這樣做,'.count'屬性(method?)不可用。但是如果'cgi'返回'128'文件,則腳本輸出'128'(即使'128.count'沒有意義)。但爲什麼這不適用於1文件夾?基本上它會返回'[int] 1.count',它仍然是'1',對吧?爲什麼我的腳本適用於文件夾中的所有文件數量,但不適用於1? – Pr0no 2015-02-06 13:03:29

+0

這是Powershell處理表達式返回的結果。如果結果是標量(單個對象),那麼結果將是該類型的一個對象。如果它返回多個對象,那麼Powershell會自動將它們打包到一個數組中。單個文件對象沒有.count屬性,因此檢查它將返回$ null。如果你施放的是[int],則結果爲0。 – mjolinor 2015-02-06 13:13:30

相關問題