2012-09-12 253 views
17

我想將路徑轉換爲PowerShell腳本中的相對路徑。 如何使用PowerShell執行此操作?如何將絕對路徑轉換爲PowerShell中的相對路徑?

例如:

Path to convert: c:\documents\mynicefiles\afile.txt 
Reference path: c:\documents 
Result:   mynicefiles\afile.txt 

而且

Path to convert: c:\documents\myproject1\afile.txt 
Reference path: c:\documents\myproject2 
Result:   ..\myproject1\afile.txt 

回答

38

我發現了一些在建,Resolve-Path

Resolve-Path -Relative 

這將返回相對於當前位置的路徑。一個簡單的用法:

$root = "C:\Users\Dave\" 
$current = "C:\Users\Dave\Documents\" 
$tmp = Get-Location 
Set-Location $root 
Resolve-Path -relative $current 
Set-Location $tmp 
+14

您也可以使用Push-Location和Pop-Location來設置位置,然後恢復到其原始值,而不是使用臨時變量。相同的基本解決方案,但沒有臨時變量。 –

1

Get-RelativePath似乎是一個辦法做到這一點。

+0

但它看起來非常複雜和緩慢。沒有更好的方法來做到這一點嗎? –

+1

複雜的緩慢和越野車。 –

+0

該鏈接不再有效 – Honzajscz

-1

這裏是一個替換的方法

$pathToConvert1 = "c:\documents\mynicefiles\afile.txt" 
$referencePath1 = "c:\documents" 
$result1 = $pathToConvert1.Substring($referencePath1.Length + 1) 
#$result1: mynicefiles\afile.txt 


$pathToConvert2 = "c:\documents\myproject1\afile.txt" 
#$referencePath2 = "c:\documents\myproject2" 
$result2 = "..\myproject" + [regex]::Replace($pathToConvert2 , ".*\d+", '') 
#$result2:   ..\myproject\afile.txt 

注:在第二種情況下參考路徑不使用。

+0

我想你已經誤解了這兩個例子。我想要一種解決方法。 –

+0

是的,我誤解了你的例子,因爲它指向文件絕對路徑。 – yantaq

+0

不是OP,但這是我正在尋找解決我的問題。謝謝 –

相關問題