gpt4 book ai didi

powershell - 如何从 Powershell 使用 FileInfo 对象

转载 作者:行者123 更新时间:2023-12-02 04:49:08 25 4
gpt4 key购买 nike

我现在开始使用 PowerShell,在使用 Unix shell 很长时间之后,我想知道如何检查文件或目录是否存在。

在 Powershell 中,为什么以下表达式中的 Exist 返回 false?

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

有没有比以下更好的方法来检查文件是否是目录:

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

最佳答案

使用Test-Path而不是System.IO.FileInfo.Exists:

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

您还可以使用-PathType来测试该位置是文件还是目录:

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

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

DirectoryInfoFileInfo 也都定义了 PSIsContainer 属性:

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

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

关于powershell - 如何从 Powershell 使用 FileInfo 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/636838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com