Get-ChildItem versus using the .NET Framework method [System.IO.Directory] :: GetFiles () directly with UNC paths

When using a UNC path (ex:) \\machine\share\dir

I can get a list of files when I use the dir

( Get-ChildItem

) command 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 PS was built on the .NET platform. Does anyone know why Get-ChildItem

would work with UNC paths while the .NET method GetFiles

returns an empty list?

+3


source to share


1 answer


[System.IO.Directory]::GetFiles()

only returns files, whereas Get-ChildItem

(and its built-in alias dir

) returns files and directories by default.

Hence, calling [System.IO.Directory]::GetFiles()

on a directory that has only subdirectories (no files) yields "nothing" (an empty array of strings)).

Another way to express it is: Get-ChildItem

is a union of [System.IO.Directory]::GetFiles()

(akin Get-ChildItem -File

, PSv3 +) and [System.IO.Directory]::GetDirectories()

(akin Get-ChildItem -Directory

, PSv3 +) or, more directly, analog [System.IO.Directory]::GetFileSystemEntries()

.

Another option is to use the .NET 4+ Enum APIs (available in PSv3 +) such as [System.IO.Directory]::EnumerateFileSystemInfos()

. For example see this answer .



There are many specific differences between Get-ChildItem

and direct use of a type [System.IO.Directory]

, but especially what Get-ChildItem

returns objects, not strings, and what Get-ChildItem

skips hidden elements by default ( -Force

should be used).

As usual, choosing between using native PowerShell cmdlets and using the .NET Framework directly is a trade-off between convenience and performance.
The latter will generally be faster, and in this case it is especially true for UNC paths in PowerShell versions 1 and 2 - see this blog post .

WOxxOm Hat tip and Mike Sherrill's "Cat Recall" review for more information.

+3


source







All Articles