如何在PowerShell中将绝对路径转换为相对路径?

Dav*_*ier 32 powershell

我想在PowerShell脚本中将路径转换为相对路径.如何使用PowerShell执行此操作?

例如:

Path to convert: c:\documents\mynicefiles\afile.txt
Reference path:  c:\documents
Result:          mynicefiles\afile.txt
Run Code Online (Sandbox Code Playgroud)

Path to convert: c:\documents\myproject1\afile.txt
Reference path:  c:\documents\myproject2
Result:          ..\myproject1\afile.txt
Run Code Online (Sandbox Code Playgroud)

Dav*_*ier 54

我找到了内置的东西,Resolve-Path:

Resolve-Path -Relative
Run Code Online (Sandbox Code Playgroud)

这将返回相对于当前位置的路径.一个简单的用法:

$root = "C:\Users\Dave\"
$current = "C:\Users\Dave\Documents\"
$tmp = Get-Location
Set-Location $root
Resolve-Path -relative $current
Set-Location $tmp
Run Code Online (Sandbox Code Playgroud)

  • 您也可以使用Push-Location和Pop-Location设置位置,然后恢复为原始值,而不是使用临时变量.相同的基本解决方案,但没有临时变量. (19认同)
  • 为了确保即使 `Resolve-Path` 抛出异常(取决于 `$ErrorActionPreference`)也能恢复当前位置,请将代码包装在 try/catch 中: `try{ push-location $root; 解析路径-相对 $current } 最后{ pop-location }` (5认同)
  • 聪明,但我不喜欢更改工作目录的副作用(即使您将其切换回) (3认同)
  • 如果根目录尚不存在,这将失败。 (2认同)

Joh*_*all 7

使用内置System.IO.Path.GetRelativePath比接受的答案更简单:

[System.IO.Path]::GetRelativePath($relativeTo, $path)
Run Code Online (Sandbox Code Playgroud)