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