【问题标题】:How do I get the absolute path based on either relative or absolute paths in PowerShell?如何根据 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 的绝对路径,同时接受绝对和相对输入,以及尚不存在的路径?

【问题讨论】:

标签: powershell path


【解决方案1】:

这个函数为我完成了这项工作:

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)

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

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

请注意,虽然.\.\C:\code\.\out 确实看起来很奇怪,但它是有效的并且解析到正确的路径。毕竟,这只是 PowerShell 集成的Join-Path 函数的输出。

【讨论】:

    猜你喜欢
    • 2012-10-25
    • 2013-04-17
    • 2013-10-27
    • 1970-01-01
    • 2010-09-21
    • 2015-02-09
    • 1970-01-01
    • 2022-06-10
    • 2012-01-11
    相关资源
    最近更新 更多