我现在开始使用PowerShell并且经过大量时间使用Unix shell并想知道如何检查文件或目录是否存在。
在Powershell中,为什么Exist
在以下表达式中返回false?
PS H:\> ([System.IO.FileInfo]"C:\").Exists
False
是否有更好的方法来检查文件是否是一个目录而不是:
PS H:\> ([System.IO.FileInfo]"C:\").Mode.StartsWith("d")
True
答案 0 :(得分:22)
使用'test-path'而不是System.IO.FileInfo.Exists
PS C:\Users\m> test-path 'C:\'
True
您可以使用PSIsContainer来确定文件是否是目录:
PS C:\Users\m> (get-item 'c:\').PSIsContainer
True
PS C:\Users\m> (get-item 'c:\windows\system32\notepad.exe').PSIsContainer
False
答案 1 :(得分:10)
除Michael's answer外,您还可以使用以下方式进行测试:
PS H:> ([System.IO.DirectoryInfo]"C:\").Exists
True
答案 2 :(得分:9)
在Powershell中,为什么Exist在下面的表达式中返回false?
PS H:> ([System.IO.FileInfo]"C:\").Exists
因为没有名为“C:\”的文件 - 它是一个目录。
答案 3 :(得分:8)
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:\
答案 4 :(得分:2)
您可以使用Get-Item
允许PowerShell在FileInfo
和DirectoryInfo
之间进行选择。如果路径未解析到某个位置,它将抛出异常。
PS> $(Get-Item "C:\").GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DirectoryInfo System.IO.FileSystemInfo
如果您需要Test-Path
或DirectoryInfo
条目,我只会在FileInfo
上使用此内容。
答案 5 :(得分:2)
这两个评估为真
$(Get-Item "C:\").GetType() -eq [System.IO.DirectoryInfo]
$(Get-Item "C:\test.txt").GetType() -eq [System.IO.FileInfo]