Warm tip: This article is reproduced from serverfault.com, please click

其他-如何在PowerShell中基于相对或绝对路径获取绝对路径?

(其他 - How do I get the absolute path based on either relative or absolute paths in PowerShell?)

发布于 2020-12-01 07:37:41

考虑以下情况:我有一个参数或配置变量,用于设置脚本的输出目录。显然,此参数也应该是绝对的:

RepoBackup.ps1 -OutputDirectory .\out
RepoBackup.ps1 -OutputDirectory D:\backup

在脚本中,我(Get-Item -Path './').FullName与结合使用Join-Path以确定我的输出目录的绝对路径,因为我可能需要使用它Set-Location来更改当前目录-这使得使用相对路径变得很复杂。

但:

Join-Path C:\code\ .\out  # => C:\code\.\out  (which is exactly what i need)
Join-Path C:\code\ D:\    # => C:\code\D:\    (which is not only not what i need, but invalid)

我考虑过使用Resolve-Path和做类似的事情Resolve-Path D:\backup,但是如果该目录不存在(尚未),则会产生关于无法找到路径的错误。

那么,如何获得我的绝对路径$OutputDirectory,接受绝对和相对输入,以及尚不存在的路径?

Questioner
sk22
Viewed
0
sk22 2020-12-01 17:15:00

此功能为我完成了工作:

function Join-PathOrAbsolute ($Path, $ChildPath) {
    if (Split-Path $ChildPath -IsAbsolute) {
        Write-Verbose ("Not joining '$Path' with '$ChildPath'; " +
            "returning the child path as it is absolute.")
        $ChildPath
    } else {
        Write-Verbose ("Joining path '$Path' with '$ChildPath', " +
            "child path is not absolute")
        Join-Path $Path $ChildPath
    }
}

# short version, without verbose messages:

function Join-PathOrAbsolute ($Path, $ChildPath) {
  if (Split-Path $ChildPath -IsAbsolute) { $ChildPath }
  else { Join-Path $Path $ChildPath }
}
Join-PathOrAbsolute C:\code .\out  # => C:\code\.\out (just the Join-Path output)
Join-PathOrAbsolute C:\code\ D:\   # => D:\ (just the $ChildPath as it is absolute)

它只是检查后一个路径是否是绝对路径,如果是绝对路径则返回它,否则它仅Join-Path$Path两者上运行$ChildPath请注意,这并不认为基础$Path是相对的,但是对于我的用例而言,这已经足够了。(我(Get-Item -Path './').FullName用作基本路径,无论如何都是绝对路径。)

Join-PathOrAbsolute .\ D:\    # => D:\
Join-PathOrAbsolute .\ .\out  # => .\.\out

请注意,虽然.\.\C:\code\.\out确实看起来很怪异,它是有效的,并解决的正确路径。Join-Path毕竟,这只是PowerShell集成功能的输出