使用[System.IO.DirectoryInfo]时Test-Path对X:与X:\的结果差异疑问
Test-Path处理DirectoryInfo对象时X:与X:\的行为差异解析
场景复现
本机不存在X:驱动器但存在C:驱动器时,使用[System.IO.DirectoryInfo]类型传入Test-Path会出现以下差异:
PS C:\> Test-Path ([System.IO.DirectoryInfo]'X:') True PS C:\> Test-Path ([System.IO.DirectoryInfo]'X:\') False PS C:\> Test-Path -Path ([System.IO.DirectoryInfo]'C:') True PS C:\> Test-Path -Path ([System.IO.DirectoryInfo]'C:\') True
同时对比X:和X:\生成的DirectoryInfo对象,属性完全一致:
[System.IO.DirectoryInfo]$GoodPath = 'X:\' [System.IO.DirectoryInfo]$BadPath = 'X:' PS C:\> $GoodPath, $BadPath | Format-List -Property * Mode : darhsl BaseName : X:\ Target : LinkType : Name : X:\ FullName : X:\ Parent : Exists : False Root : X:\ Extension : CreationTime : 12/31/1600 4:00:00 PM CreationTimeUtc : 1/1/1601 12:00:00 AM LastAccessTime : 12/31/1600 4:00:00 PM LastAccessTimeUtc : 1/1/1601 12:00:00 AM LastWriteTime : 12/31/1600 4:00:00 PM LastWriteTimeUtc : 1/1/1601 12:00:00 AM Attributes : -1 Mode : darhsl BaseName : X:\ Target : LinkType : Name : X:\ FullName : X:\ Parent : Exists : False Root : X:\ Extension : CreationTime : 12/31/1600 4:00:00 PM CreationTimeUtc : 1/1/1601 12:00:00 AM LastAccessTime : 12/31/1600 4:00:00 PM LastAccessTimeUtc : 1/1/1601 12:00:00 AM LastWriteTime : 12/31/1600 4:00:00 PM LastWriteTimeUtc : 1/1/1601 12:00:00 AM Attributes : -1
通过Trace-Command追踪参数绑定,发现X:对应的绑定路径为[.],X:\绑定为[X:\];C:绑定为[.]、C:\绑定为[C:\]但均返回True。
1. 为何X:和X:\在此场景下表现不同?
核心原因在于PowerShell的参数绑定与路径解析逻辑:
- 当传入
[System.IO.DirectoryInfo]'X:'时,由于X:驱动器不存在,PowerShell会将这种不带根路径的驱动器号解析为当前会话的工作目录(即你当前所在的C:\下的目录,对应路径[.]),而该目录是存在的,因此Test-Path返回True。 - 而
[System.IO.DirectoryInfo]'X:\'明确指向X盘的根目录,由于X:驱动器本身不存在,这个路径无法访问,因此Test-Path返回False。
虽然两个DirectoryInfo对象的属性(如FullName)都显示为X:\,但PowerShell在处理Test-Path的参数绑定时,会对未映射驱动器的路径做特殊解析,优先使用当前工作目录作为 fallback。
2. 为何C:和C:\没有这种差异?
因为C:是已存在的有效驱动器:
[System.IO.DirectoryInfo]'C:'被解析为C:驱动器的当前工作目录(即你当前所在的C:\下的位置,对应[.]),该目录是存在的。[System.IO.DirectoryInfo]'C:\'直接指向C盘的根目录,同样是存在的有效路径。
两者指向的都是C盘上的有效目录,因此Test-Path均返回True。
内容的提问来源于stack exchange,提问作者Paul π
相关产品推荐
相关产品推荐

