从PowerShell中的绝对路径获取相对路径

时间:2012-11-05 20:12:47

标签: string powershell path relative-path absolute-path

问题

您有一条绝对路径,但您希望它相对于另一条路径。

示例:

P:/SO/data/database.txt

--> Now we want the filename to be relative to: P:/SO/team/lists/
../../data/database.txt

我已经找到了Stack Overflow 问题 How to convert absolute path to relative path in PowerShell?

一个答案链接到already developed Cmdlet,但这个答案对我不起作用。使用Set/Get-Location的技巧需要存在路径。

1 个答案:

答案 0 :(得分:1)

解决方案

我找到了用PHP编写的Gordon的答案: Getting relative path from absolute path in PHP

这是我的PowerShell端口:

<# This is probably not the best code I've ever written, but
   I think it should be readable for most (advanced) users.

   I will wrap this function into a Cmdlet when I have time to do it.
   Feel free to edit this answer and improve it!
#>
function getRelativePath([string]$from, [string]$to, [string]$joinSlash='/') {

    $from = $from -replace "(\\)", "/";
    $to = $to -replace "(\\)", "/";

    $fromArr = New-Object System.Collections.ArrayList;
    $fromArr.AddRange($from.Split("/"));

    $relPath = New-Object System.Collections.ArrayList;
    $relPath.AddRange($to.Split("/"));


    $toArr = New-Object System.Collections.ArrayList;
    $toArr.AddRange($to.Split("/"));

    for ($i=0; $i -lt $fromArr.Count; $i++) {
        $dir = $fromArr[$i];

        # Find first non-matching directory
        if ($dir.Equals($toArr[$i])) {
            # ignore this directory
            $relPath.RemoveAt(0);
        }
        else {
            # Get number of remaining directories to $from
            $remaining = $fromArr.Count - $i;
            if ($remaining -gt 1) {
                # Add traversals up to first matching directory
                $padLength = ($relPath.Count + $remaining - 1);

                # Emulate array_pad() from PHP
                for (; $relPath.Count -ne ($padLength);) {
                    $relPath.Insert(0, "..");
                }
                break;
            }
            else {
                $relPath[0] = "./" + $relPath[0];
            }
        }
    }
    return $relPath -Join $joinSlash;
}

<强>注意:    - 你 From 路径必须以斜杠结束!

实施例

getRelativePath -From "P:/SO/team/lists/" -To "P:/SO/data/database.txt";
--> ../../data/database.txt

getRelativePath -From "C:/Windows/System32/" -To "C:/Users/ComFreek/Desktop/SO.txt";
--> ../../Users/ComFreek/Desktop/SO.txt