如何在PowerShell中获取Windows显示的大小写敏感路径(适配WSL)
获取Windows文件的实际大小写路径(适配WSL)
我完全理解你的痛点——Windows的不区分大小写路径在WSL的大小写敏感环境里简直是个坑,尤其是当你需要准确调用文件的时候。下面是几个实用的方法,帮你获取文件的实际大小写路径:
方法1:用PowerShell直接获取(Windows端)
PowerShell可以调用Windows底层API获取文件的真实大小写路径,操作很简单:
# 替换成你要查询的路径 $targetPath = "C:\foo\bar.txt" # 获取实际大小写路径 $actualPath = (Get-Item -Path $targetPath).FullName # 输出结果 Write-Output $actualPath
执行后会返回文件系统中实际存储的大小写路径,比如C:\Foo\BAR.txt。
方法2:在WSL中直接查询(一键转换)
如果你不想切换到Windows命令行,可以在WSL的bash/zsh里直接调用Windows工具来转换:
# 替换成你在WSL里的路径 wsl_path="/mnt/c/foo/bar.txt" # 步骤1:转换为Windows格式路径 windows_path=$(wslpath -w "$wsl_path") # 步骤2:调用PowerShell获取真实大小写路径 actual_windows_path=$(powershell.exe -Command "(Get-Item -Path '$windows_path').FullName") # 步骤3:转换回WSL格式路径 actual_wsl_path=$(wslpath -u "$actual_windows_path") # 输出结果 echo $actual_wsl_path
运行后会直接输出WSL可用的准确大小写路径,比如/mnt/c/Foo/BAR.txt。
方法3:用Windows的fsutil工具(需管理员权限)
fsutil是Windows自带的文件系统工具,能查询文件的详细信息,包括真实文件名:
# 替换成目标路径 fsutil file queryfileinfo c:\foo\bar.txt | findstr "File Name"
输出结果会包含类似File Name : c:\foo\BAR.txt的内容,从中就能提取到实际大小写的路径。
方法4:Python脚本(跨平台调用)
如果你熟悉Python,可以写个小脚本调用Windows API来获取真实路径,适合自动化场景:
import ctypes from ctypes import wintypes def get_real_case_path(path): MAX_PATH = 260 buffer = ctypes.create_unicode_buffer(MAX_PATH) # 调用Windows API GetLongPathNameW获取真实路径 result = ctypes.windll.kernel32.GetLongPathNameW(path, buffer, MAX_PATH) if result == 0 or result > MAX_PATH: return path # 出错时返回原路径 return buffer.value # 示例使用 print(get_real_case_path("C:\\foo\\bar.txt"))
这个脚本会直接返回文件的实际大小写路径,你也可以在WSL里通过python.exe调用它(前提是Windows端安装了Python)。
内容的提问来源于stack exchange,提问作者Eric




