Where to apply -ErrorAction on a .Net call?

后端 未结 2 1209
旧时难觅i
旧时难觅i 2020-12-22 02:46

This works to count *.jpg files.

PS C:\\> @([System.IO.Directory]::EnumerateFiles(\'C:\\Users\\Public\\Pictures\', \'*.jpg\', \'AllDirectories\')).Count
8         


        
相关标签:
2条回答
  • 2020-12-22 03:03

    Ansgar Wiechers' helpful answer shows a workaround using Get-ChildItem, which is necessary when using the full, Windows-only .NET Framework (FullCLR), on which Windows PowerShell is built.

    By contrast, .NET Core v2.1+ - on which PowerShell Core is built - does offer a solution:

    @([System.IO.Directory]::EnumerateFiles(
      'C:\Users',
      '*.jpg', 
      [System.IO.EnumerationOptions] @{ 
        IgnoreInaccessible = $true
        RecurseSubDirectories = $true
      }
    )).Count
    

    Note that this is the equivalent of -ErrorAction Ignore, not Continue (or SilentlyContinue, in that inaccessible are quietly ignored, with no way to examine what directories were inaccessible afterwards.

    The solution is based on this System.IO.Directory.EnumerateFiles() overload, which offers a System.IO.EnumerationOptions parameter.

    0 讨论(0)
  • 2020-12-22 03:07

    I don't think you can. Unless you want to implement directory traversal yourself you're probably stuck with something like this:

    Get-ChildItem 'C:\Users' -Filter '*.jpg' -Recurse -Force -ErrorAction SilentlyContinue
    
    0 讨论(0)
提交回复
热议问题