【问题标题】:How to normalize and compare paths in Powershell如何在 Powershell 中规范化和比较路径
【发布时间】:2022-10-01 20:13:00
【问题描述】:

我需要测试两个包含路径的字符串,看它们是否指向同一个目录。
例如,在比较 C:\\WindowsC:\\Windows\\ 时,简单地使用字符串比较会失败。

这个问题可以通过使用 this StackOverflow-Question 的 Join-Path 来解决,但它仍然遗漏了其他事情:
例如\\\\server\\share 有时可以表示为UNC\\server\\share\\\\<ip>\\share

有没有正确的方法来检查这个而不使用解决方法?

编辑: 我已经在我的 powershell 模块 PSHelperTools 中实现了我的答案中找到的代码,可以使用Install-Module PSHelperTools 下载

  • 这回答了你的问题了吗? How to normalize a path in PowerShell?
  • UNC\\server\\share不是UNC 路径,它只是一个相对本地路径。你的意思是\\\\.\\UNC\\server\\share
  • @JeffZeitlin 它不适用于我的情况,因为正如 mathias 所提到的,它被识别为相对本地路径
  • @MathiasR.Jessen 我从中获得该格式的是链接到共享的符号链接,如图所示 here
  • @MathiasR.Jessen 你不是说\\\\?\\UNC\\server\\share 吗?

标签: powershell path


【解决方案1】:

现在我使用它作为一种解决方法:

function Format-Path(){
    [Cmdletbinding()]
    param($Path)

    Write-Verbose "Format-Path: $Path"
    if($Path.StartsWith(".")){
        #Get Absolute path if path starts with "."
        $Path = Resolve-Path -Path $Path
        Write-Verbose "Resolved Path: $Path"
    }
    if($Path -match "^.*::(.*)"){
        $Path = $Path -replace "^.*::(.*)", '$1'
        Write-Verbose "Replaced Powershell providers: $Path"
    }
    $Path = $Path -replace "/"                      , "\" `
                  -replace "^\\\\\.\\"              , "" `
                  -replace "^\\\\\?\\"              , "" `
                  -replace "^UNC\\"                 , "\\"
    Write-Verbose "Replaced UNC conventions: $Path"

    if($Path -match "^\\\\([A-Za-z]+)(@SSL)?"){
        $Path = $Path -replace "^\\\\([A-Za-z]+)(@SSL)?", "\\$((Resolve-DnsName $matches[1] -Type "A").IPAddress)"
        Write-Verbose "Resolve name into IP: $Path"
    }

    return $Path.TrimEnd("\")
}

【讨论】:

    猜你喜欢
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 2010-11-17
    • 2016-08-29
    • 2010-12-17
    • 2019-10-12
    相关资源
    最近更新 更多