如何获取文件路径中指定目录为止的完整路径?
更优的PowerShell路径截取方案
针对你需要从脚本路径中提取到仓库目录(my-repo)的需求,这里提供几种更优雅高效的实现方式:
方法一:字符串直接截取(最高效)
如果确定仓库名在路径中只会出现一次,直接用字符串索引操作比正则快得多:
$fullPath = $MyInvocation.MyCommand.Path $repoName = 'my-repo' # 找到仓库名的起始位置,截取到仓库名末尾 $repoPath = $fullPath.Substring(0, $fullPath.IndexOf($repoName) + $repoName.Length)
方法二:递归遍历父目录(更鲁棒)
如果不确定仓库名在路径中的层级,或者担心路径中出现重复的仓库名字符串,可以通过遍历父目录定位:
$fullPath = $MyInvocation.MyCommand.Path $repoName = 'my-repo' $currentDir = Split-Path -Path $fullPath -Parent # 向上遍历直到找到目标目录 while ($currentDir -and (Split-Path -Path $currentDir -Leaf) -ne $repoName) { $currentDir = Split-Path -Path $currentDir -Parent } $repoPath = $currentDir
方法三:使用.NET DirectoryInfo对象(面向对象风格)
利用.NET的目录信息对象,通过Parent属性向上遍历,可读性更强:
$fullPath = $MyInvocation.MyCommand.Path $repoName = 'my-repo' # 先获取脚本所在目录的DirectoryInfo对象 $dirInfo = [System.IO.DirectoryInfo]::new((Split-Path -Path $fullPath -Parent)) # 向上查找直到匹配仓库名 while ($dirInfo -and $dirInfo.Name -ne $repoName) { $dirInfo = $dirInfo.Parent } $repoPath = $dirInfo.FullName
原方法的问题
你之前用正则Split的方式存在两个明显缺陷:
- 效率低:正则表达式的拆分操作比原生字符串操作或目录遍历开销大;
- 鲁棒性差:如果路径中存在多个与仓库名相同的子串(比如某个子目录也叫
my-repo),会导致截取结果错误。
内容的提问来源于stack exchange,提问作者jerdub1993
相关产品推荐
相关产品推荐

