41

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
4

6 に答える 6

67

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
于 2012-09-12T21:13:36.510 に答える
0

迅速かつ簡単な方法は次のとおりです。

$current -replace [regex]::Escape($root), '.'

または、実際の現在の場所からの相対パスが必要な場合

$path -replace [regex]::Escape((pwd).Path), '.'

これは、すべてのパスが有効であることを前提としています。

于 2018-09-06T15:01:23.413 に答える
-4

ここに別のアプローチがあります

$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

注: 2 番目のケースでは、ref パスは使用されませんでした。

于 2015-10-22T22:47:59.803 に答える