BeWarned
BeWarned

Reputation: 2338

How to use FileInfo object from Powershell

I am now starting to use PowerShell and after a lot of time using the Unix shells and want to know how to check for the existence of a file or directory.

In Powershell why does Exist return false in the following expression?

PS H:\> ([System.IO.FileInfo]"C:\").Exists
False

And is there a better way to check if a file is a directory than:

PS H:\> ([System.IO.FileInfo]"C:\").Mode.StartsWith("d")
True

Upvotes: 22

Views: 59208

Answers (7)

Michael
Michael

Reputation: 55435

Use Test-Path instead of System.IO.FileInfo.Exists:

PS> Test-Path -Path 'C:\'
True

You can also use -PathType to test whether the location is a file or directory:

PS> Test-Path -Path 'C:\' -PathType Container
True

PS> Test-Path -Path 'C:\' -PathType Leaf
False

DirectoryInfo and FileInfo also both define a PSIsContainer property:

PS> (Get-Item -Path 'C:\').PSIsContainer
True

PS> (Get-Item -Path 'C:\windows\system32\notepad.exe').PSIsContainer
False

Upvotes: 29

Kirt Carson
Kirt Carson

Reputation: 97

I see the best answer above using get-item, but original question used [System.IO.FileInfo] so I'll pose an answer.

[System.IO.FileInfo]"C:\Users\carsonk" | select *

Above will show most of the available attributes not shown in the default table view. There are some PS built-in attributes such as PSIsContainer that won't show by select *

PSIsContainer is not available with [System.IO.FileInfo] so

If(([System.IO.FileInfo]"C:\Users\carsonk").directory) {$True}
True

Upvotes: 0

Ybot
Ybot

Reputation: 111

Both of these evaluate to true

$(Get-Item "C:\").GetType() -eq [System.IO.DirectoryInfo]
$(Get-Item "C:\test.txt").GetType() -eq [System.IO.FileInfo]

Upvotes: 4

Doug Finke
Doug Finke

Reputation:

Help Test-Path

Test-Path Determines whether all elements of a path exist

Test-Path -PathType Leaf C:\test.txt
Test-Path -PathType Container C:\
Test-Path C:\

Upvotes: 10

jdmichal
jdmichal

Reputation: 11162

You can use Get-Item to allow PowerShell to select between FileInfo and DirectoryInfo. It will throw an exception if the path doesn't resolve to a location.

PS> $(Get-Item "C:\").GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     DirectoryInfo                            System.IO.FileSystemInfo

I would only use this over Test-Path if you will need the DirectoryInfo or FileInfo entry if it does exist.

Upvotes: 3

Kev
Kev

Reputation: 119836

In addition to Michael's answer you could also test using:

PS H:> ([System.IO.DirectoryInfo]"C:\").Exists
True

Upvotes: 13

Jay Bazuzi
Jay Bazuzi

Reputation: 46536

In Powershell why does Exist return false in the following expression?

  PS H:> ([System.IO.FileInfo]"C:\").Exists
  

Because there is no file called "C:\" - it's a directory.

Upvotes: 14

Related Questions