Ray
Ray

Reputation: 8573

Powershell gettting parent directory doesn't work with ordinary files when listed by `dir`

The following doesn't work:

function WTF {
  foreach ($Path in $(dir)) {
    echo $(Get-Item $Path).parent
  }
}

If the current directory contains subdirectories, then their parents will be printed, but it doesn't work on ordinary files. Why not?

Upvotes: 0

Views: 282

Answers (1)

vonPryz
vonPryz

Reputation: 24071

This happens, as Get-ChildItem returns an array of objects. The catch is that an array in Powershell can contain objects of different types. Get-ChildItem will populate the array with FileInfo objects for files, and DirectoryInfo objects for directories.

The FileInfo class doesn't have .Parent member, but DirectoryInfo does. Thus the disparity in the results.

If one tries to use a strongly typed array, it won't end up well:

[IO.FileInfo[]]$ff = gci
Cannot convert the "SampleDirectory" value of type
  "System.IO.DirectoryInfo" to type "System.IO.FileInfo".
At line:1 char:1
+ [IO.FileInfo[]]$ff = gci

Assuming you have a directory with files and subdirectories, it's easy to check what'll gci will return. In my test directory, the first entry is a directory and the last is a file. The results for calling .GetType() are like so,

$ff=gci
$ff[0].gettype()
IsPublic IsSerial Name            BaseType
-------- -------- ----            --------
True     True     DirectoryInfo   System.IO.FileSystemInfo


$ff[-1].gettype()
IsPublic IsSerial Name            BaseType
-------- -------- ----            --------
True     True     FileInfo        System.IO.FileSystemInfo

Upvotes: 2

Related Questions