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

标签 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

我已经发现堆栈溢出
问题How to convert absolute path to relative path in PowerShell?

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

最佳答案

解决方案

我从用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;
}

注意:
-您来自路径必须以斜线结尾!


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

关于string - 从PowerShell中的绝对路径获取相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13239620/

相关文章:

javascript - 如何将字符串添加到变量;

unit-testing - Pester 中的 Assert-MockCalled 与 Assert-VerABLEMocks

powershell - 如何通过脚本设置Azure DevOps版本的描述?

量化线段路径差异的算法

c++ - 试图计算我的 "sir"(字符串)类的 ASCII 码总和

c++ - 在 C++ 中连接 3 个或更多元素的字符串 (string[i]+string[i+1]+string[i+2])

php - 如何在 PHP 中获取符号链接(symbolic link)的原始路径?

c++ - 长格式和多格式路径操作库?

php - 从 Google map img 的 src 中提取坐标

powershell 包含不工作