【问题标题】:Create new absolute path from absolute path + relative or absolute path从绝对路径+相对或绝对路径创建新的绝对路径
【发布时间】:2015-03-21 22:36:57
【问题描述】:

我正在使用 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,但我无法找到任何有关如何做我想做的事的资源。有没有简单的一行来完成我需要的?

【问题讨论】:

    标签: powershell psake


    【解决方案1】:

    您可以使用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】:

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

      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
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-04-17
        • 2012-10-16
        • 2015-02-09
        • 1970-01-01
        • 2012-01-11
        • 2010-09-15
        • 1970-01-01
        • 1970-01-01
        • 2013-07-14
        相关资源
        最近更新 更多