Where to apply -ErrorAction on a .Net call?

后端 未结 2 1208
旧时难觅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.

提交回复
热议问题