PowerShell如何实现输入文件名即可查询对应完整文件路径
PowerShell查找文件/文件夹完整路径方案
方法1:直接运行内置命令(临时使用推荐,无需写脚本)
PowerShell自带的Get-ChildItem命令即可实现需求,直接复制下面的命令修改搜索内容后执行即可:
# 模板:把<目标名称>换成你要找的文件名/文件夹名,<盘符>换成你要搜索的磁盘根路径比如C:\ Get-ChildItem -Path <盘符> -Filter "<目标名称>" -Recurse -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName
示例
- 查找C盘中所有test.txt的全路径:
Get-ChildItem -Path C:\ -Filter "test.txt" -Recurse -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName - 查找D盘中My Documents文件夹的全路径:
Get-ChildItem -Path D:\ -Filter "My Documents" -Recurse -ErrorAction SilentlyContinue | Select-Object -ExpandProperty FullName
也可以用简写版本,效果完全一致:gci C:\ -Filter "test.txt" -r -ea 0 | select FullName
方法2:封装为可重复使用的脚本(频繁使用推荐)
把以下代码保存为后缀为.ps1的文件(比如FindFullPath.ps1),需要使用时右键点击该文件,选择「使用PowerShell运行」即可:
# 读取用户输入的目标名称 $target = Read-Host "请输入你要查找的文件/文件夹名称" # 读取搜索根路径 $searchPath = Read-Host "请输入要搜索的根盘符(如C:\,直接回车则搜索所有本地磁盘)" # 没有输入盘符时自动获取所有本地磁盘 if ([string]::IsNullOrEmpty($searchPath)) { $localDisks = (Get-Volume | Where-Object { $_.DriveType -eq 'Fixed' -and $_.DriveLetter }).DriveLetter | ForEach-Object { $_ + ":\" } } else { $localDisks = @($searchPath) } # 遍历搜索并输出全路径 foreach ($disk in $localDisks) { Get-ChildItem -Path $disk -Filter $target -Recurse -ErrorAction SilentlyContinue | ForEach-Object { Write-Host $_.FullName } } Write-Host "搜索完成,按任意键关闭窗口" [Console]::ReadKey() | Out-Null
使用说明
- 运行后按照提示输入要查找的名称即可,支持文件名(如test.txt)和文件夹名(如My Documents)
- 同名的所有文件/文件夹路径都会全部输出
- 首次全盘搜索可能需要等待数十秒,具体耗时取决于磁盘文件总量
内容的提问来源于stack exchange,提问作者M4squerade
相关产品推荐
相关产品推荐

