PowerShell中无需切换工作目录解析非存在相对路径的方法
PowerShell中解析非存在路径的原生替代方案
在PowerShell v5或Core版本中,确实存在无需切换工作目录的原生方法,可替代你自定义的Resolve-RelativePath函数,满足基于指定基础路径解析可能不存在的路径、且兼容绝对路径输入的需求。
原生解决方案
直接使用$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath()方法的重载版本,该方法支持传入基础路径作为第二个参数,无需通过Push-Location/Pop-Location切换目录,完全避免副作用。
替代的简化函数如下:
Function Resolve-RelativePath-Native { Param ( [Parameter(Mandatory)] [string]$Path , [Parameter()] [string]$BasePath = '.' ) # 直接传入基础路径,无需切换目录 $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path, $BasePath) }
验证测试
使用你提供的测试用例验证,所有结果均返回true:
# 确保基础路径存在 New-Item -Path 'c:\temp\demo\ChildFolderThatExists' -ItemType Directory -Force | Out-Null New-Item -Path 'c:\temp\demo2\ChildFolderThatExists' -ItemType Directory -Force | Out-Null Set-Location -Path 'c:\temp\demo' # 测试原生方法 (Resolve-RelativePath-Native -Path 'ChildFolderThatExists' ) -eq 'c:\temp\demo\ChildFolderThatExists' (Resolve-RelativePath-Native -Path 'ChildFolderThatDoesntExist' ) -eq 'c:\temp\demo\ChildFolderThatDoesntExist' (Resolve-RelativePath-Native -Path '../../someOtherFolder/Whatever' ) -eq 'c:\someOtherFolder\Whatever' (Resolve-RelativePath-Native -Path 'c:\absolute' ) -eq 'c:\absolute' (Resolve-RelativePath-Native -Path 'ChildFolderThatExists' -BasePath 'c:\temp\demo2' ) -eq 'c:\temp\demo2\ChildFolderThatExists' (Resolve-RelativePath-Native -Path 'ChildFolderThatDoesntExist' -BasePath 'c:\temp\demo2' ) -eq 'c:\temp\demo2\ChildFolderThatDoesntExist' (Resolve-RelativePath-Native -Path '../../someOtherFolder/Whatever' -BasePath 'c:\temp\demo2') -eq 'c:\someOtherFolder\Whatever' (Resolve-RelativePath-Native -Path 'c:\absolute' -BasePath 'c:\temp\demo2' ) -eq 'c:\absolute'
方法说明
- 该方法会自动处理路径类型:若传入的
Path是绝对路径,直接返回该绝对路径;若为相对路径,则基于BasePath解析为完整路径。 - 要求
BasePath必须存在(与你原函数的约束一致),但目标路径可以不存在。
内容的提问来源于stack exchange,提问作者JohnLBevan
相关产品推荐
相关产品推荐

