用 Test-Path 判断文件或文件夹是否存在

PowerShell 里最常忘的布尔存在性检查,适用于文件、目录、注册表路径,还支持通配符。

Windows文件脚本PowerShell低风险
运行 Test-Path '<路径>',存在返回 True,不存在返回 False;脚本中常用 if (Test-Path ...) 做守卫。

01命令

命令
$ Test-Path 'C:\Program Files\Git\bin\git.exe'

02作用说明

Test-Path 对任何 PowerShell 提供程序的路径都有效:文件系统、注册表(HKLM:\...)、环境变量等。-PathType Leaf 只匹配文件,-PathType Container 只匹配目录,避免把目录当成同名文件。-IsValid 只校验路径字符串语法,不实际访问磁盘。

03风险

风险低风险
使用条件PowerShell
!注意: 在某些网络共享上,对无权限探测的路径 Test-Path 也返回 False,不要把 False 理解为“文件一定不存在”。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

  • Test-Path | Microsoft Learn
    Microsoft · vendor-doc · 2026-09-17
    依据: Microsoft documents Test-Path returning $True/$False for an existing path, plus -PathType Leaf/Container and -IsValid syntax checks.
  • Test-Path - PowerShell
    SS64 · technical · 2026-09-17
    依据: SS64 shows Test-Path examples including if (Test-Path ...) guards and the -IsValid parameter for validating path syntax.

最后验证: 2026-09-17 · 分类: 文件与文件夹

06相关方案