You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中提取ABC开头exe文件所在目录路径的方法

获取目标EXE文件所在目录的PowerShell实现方法

方案一:修改原查找函数直接返回目录路径

原函数返回的是文件完整路径,其实可以直接在Get-ChildItem的结果中提取目录信息,这样更高效,不需要额外处理路径字符串:

function findPath ($path) {
    # 直接返回文件所在目录的完整路径
    return Get-ChildItem -Path $path -Filter '*ABC*.exe' -Recurse | ForEach-Object { $_.Directory.FullName }
}

或者用$_.DirectoryName属性,效果完全一致:

function findPath ($path) {
    return Get-ChildItem -Path $path -Filter '*ABC*.exe' -Recurse | ForEach-Object { $_.DirectoryName }
}

方案二:基于现有函数返回的路径提取目录

如果不想修改原findPath函数,拿到返回的文件完整路径后,可以用以下几种方式提取目录:

  • 使用PowerShell原生Split-Path命令(最常用):
$fileFullPath = findPath "C:\Users\UserX\Desktop"
$dirPath = Split-Path -Path $fileFullPath -Parent
  • 调用.NET的System.IO.Path类方法:
$fileFullPath = findPath "C:\Users\UserX\Desktop"
$dirPath = [System.IO.Path]::GetDirectoryName($fileFullPath)
  • 将路径转为文件对象后提取目录:
$fileFullPath = findPath "C:\Users\UserX\Desktop"
$dirPath = (Get-Item $fileFullPath).Directory.FullName

注意:如果查找结果匹配到多个EXE文件,以上方法会返回所有对应目录;如果只需要单个结果,可以在管道中添加| Select-Object -First 1来限制输出数量。

内容的提问来源于stack exchange,提问作者eagerdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 08:48:21