views:

1599

answers:

4

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 files is a directory than:

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

True

Thanks

+10  A: 

Use 'test-path' instead of System.IO.FileInfo.Exists

PS C:\Users\m> test-path 'C:\'
True

You can use PSIsContainer to determine if a file is a directory:

PS C:\Users\m> (get-item 'c:\').PSIsContainer
True

PS C:\Users\m> (get-item 'c:\windows\system32\notepad.exe').PSIsContainer
False
Michael
+4  A: 

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:\

+3  A: 

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

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

HTH
Kev

Kev
+2  A: 

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.

Jay Bazuzi
I'm used to Unix where a directory is a file too.
BeWarned