4

When using a UNC path (ex: \\machine\share\dir), I can get a file list when using the dir command (Get-ChildItem) from a UNC path, but if I try [System.IO.Directory]::GetFiles, I get an empty list (not an error, just no items). I thought that PS was built on the .NET framework. Does anyone know why Get-ChildItem would work with a UNC path while the .NET GetFiles method returns an empty list?

mklement0
  • 382,024
  • 64
  • 607
  • 775
Dweeberly
  • 4,668
  • 2
  • 22
  • 41
  • 2
    GetFileSystemEntries method would be the analog you're looking for. Also, the difference is that NET class is faster, especially with UNC parts. – wOxxOm Jul 30 '17 at 04:07

1 Answers1

6

[System.IO.Directory]::GetFiles() returns only files, whereas Get-ChildItem (and its built-in alias dir) by default returns both files and directories.

Therefore, calling [System.IO.Directory]::GetFiles() on a directory that has sub-directories only (no files) yields "nothing" (an empty string array)).

Another way of putting it, loosely speaking: Get-ChildItem is the union of [System.IO.Directory]::GetFiles() (akin to Get-ChildItem -File, PSv3+) and [System.IO.Directory]::GetDirectories() (akin to Get-ChildItem -Directory, PSv3+), or, more directly, the counterpart to [System.IO.Directory]::GetFileSystemEntries().

Another option is to use the .NET 4+ (available in PSv3+) filesystem-item enumeration APIs, such as [System.IO.Directory]::EnumerateFileSystemInfos(). For an example, see this answer of mine.

There are many specific differences between Get-ChildItem and direct use of the [System.IO.Directory] type, however, notably that Get-ChildItem returns objects rather than strings and that Get-ChildItem skips hidden items by default (-Force must be used).

As is typical, choosing between using PowerShell's own cmdlets and direct use of the .NET Framework is a tradeoff between convenience and performance.
The latter will generally be faster, and in the case at hand, that is especially true with UNC paths in PowerShell versions 1 and 2 - see this blog post.

Tip of the hat to wOxxOm and Mike Sherrill 'Cat Recall' for supplemental information.

mklement0
  • 382,024
  • 64
  • 607
  • 775