代码之家  ›  专栏  ›  技术社区  ›  Matthew

从绝对路径+相对或绝对路径创建新的绝对路径

  •  1
  • Matthew  · 技术社区  · 9 年前

    我正在使用psake编写一个构建脚本,我需要从当前工作目录创建一个绝对路径,输入的路径可以是相对路径,也可以是绝对路径。

    假设当前位置为 C:\MyProject\Build

    $outputDirectory = Get-Location | Join-Path -ChildPath ".\output"
    

    给予 C:\MyProject\Build\.\output ,这并不可怕,但我希望没有 .\ 。我可以使用 Path.GetFullPath .

    当我想提供绝对路径时,问题就出现了

    $outputDirectory = Get-Location | Join-Path -ChildPath "\output"
    

    给予 C:\MyProject\Build\output ,在我需要的地方 C:\output 相反

    $outputDirectory = Get-Location | Join-Path -ChildPath "F:\output"
    

    给予 C:\MyProject\Build\F:\output ,在我需要的地方 F:\output 相反

    我试过使用 Resolve-Path ,但这总是抱怨路径不存在。

    我想 Join-Path 不是要使用的cmdlet,但我无法找到有关如何执行所需操作的任何资源。有没有一条简单的路线可以满足我的需求?

    2 回复  |  直到 9 年前
        1
  •  2
  •   Community Neeleshkumar S    7 年前

    你可以使用 GetFullPath() ,但您需要使用“hack”使其使用当前位置作为当前目录(以解析相对路径)。在使用修复程序之前,.NET方法的当前目录是进程的工作目录,而不是您在PowerShell进程中指定的位置。看见 Why don't .NET objects in PowerShell use the current directory?

    #Hack to make .Net methods use the shells current directory instead of the working dir for the process
    [System.Environment]::CurrentDirectory = (Get-Location)
    ".\output", "\output", "F:\output" | ForEach-Object {
        [System.IO.Path]::GetFullPath($_)
    }
    

    输出:

    C:\Users\Frode\output
    C:\output
    F:\output
    

    这样的事情应该对你有用:

    #Hack to make .Net methods use the shells current directory instead of the working dir for the process
    [System.Environment]::CurrentDirectory = (Get-Location)
    
    $outputDirectory = [System.IO.Path]::GetFullPath(".\output")
    
        2
  •  2
  •   user2226112 user2226112    9 年前

    我认为没有简单的一行。但我假设你需要创建路径,如果它还不存在的话?那么为什么不测试并创建它呢?

    cd C:\
    $path = 'C:\Windows', 'C:\test1', '\Windows', '\test2', '.\Windows', '.\test3'
    
    foreach ($p in $path) {
        if (Test-Path $p) {
            (Get-Item $p).FullName
        } else {
            (New-Item $p -ItemType Directory).FullName
        }
    }