How to use FileInfo object from Powershell

BeWarned picture BeWarned · Mar 12, 2009 · Viewed 47k times · Source

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

Answer

Michael picture Michael · Mar 12, 2009

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