约 2033 字

约 10 分钟

#PowerShell 的 Test-Path 命令

Test-Path
    [-Path] <String[]>
    [-Filter <String>]
    [-Include <String[]>]
    [-Exclude <String[]>]
    [-PathType <TestPathType>]
    [-IsValid]
    [-Credential <PSCredential>]
    [-OlderThan <DateTime>]
    [-NewerThan <DateTime>]
    [<CommonParameters>]

功能

确定路径的所有元素是否存在,并返回布尔值。

类型

Cmdlet,属于 Microsoft.PowerShell.Management。

参数

  • [-Path] <String[]> - 要测试的路径;支持通配符
  • -LiteralPath <String[]> - 按字面值解释路径,不将任何字符视为通配符
  • -PathType <TestPathType> - 指定路径最后元素的类型,别名 Type;可用值:
    • Any - 容器或叶子元素
    • Container - 包含其他元素的容器,例如目录或注册表项
    • Leaf - 不包含其他元素的叶子元素,例如文件
  • -IsValid - 只验证路径语法是否有效,不检查路径是否存在
  • -Filter <String> - 由提供程序执行的筛选器,通常比 -Include 更高效
  • -Include <String[]> - 只测试匹配的路径
  • -Exclude <String[]> - 排除匹配的路径
  • -NewerThan <DateTime> - 测试项的修改时间是否晚于指定时间;仅适用于 FileSystem
  • -OlderThan <DateTime> - 测试项的修改时间是否早于指定时间;仅适用于 FileSystem

#示例

检查路径是否存在

> Test-Path -Path ./README.md
True
  • 只有路径中的所有元素都存在时才返回 $true。

检查目录是否存在

> Test-Path -Path ./docs -PathType Container
  • -PathType Container 要求最终元素是目录或注册表项等容器。

检查文件是否存在

> Test-Path -Path ./docs -PathType Leaf
  • -PathType Leaf 要求最终元素是文件等叶子元素。

验证路径语法

> Test-Path -Path './new file.txt' -IsValid
True
  • -IsValid 只检查路径语法,不要求文件已经存在。

检查最近修改的文件

> Test-Path -Path ./app.log -NewerThan (Get-Date).AddHours(-1)
  • 返回 $true 表示文件在一小时内被修改过。
  • -NewerThan 和 -OlderThan 是 FileSystem 提供程序的动态参数。

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2