【问题标题】:Why is PowerShell resolving paths from $home instead of the current directory?为什么 PowerShell 从 $home 而不是当前目录解析路径?
【发布时间】:2011-10-11 21:53:18
【问题描述】:

我希望这个小的 powershell one liner 能够回显 foo.txt 的完整路径,该目录是我的当前目录。

[System.IO.Path]::GetFullPath(".\foo.txt")

但事实并非如此。它打印...

C:\Documents and Settings\Administrator\foo.txt

我不在 $home 目录中。为什么会在那里解决?

【问题讨论】:

  • 你应该在 powershell 中使用 Resolve-Path。
  • 在某些系统上,它返回相对于 c:\Windows\system32。

标签: powershell


【解决方案1】:

[System.IO.Path] 正在使用 shell 进程的当前目录。您可以使用Resolve-Path cmdlet 获取绝对路径:

Resolve-Path .\foo.txt

【讨论】:

  • 这种行为不直观,并且与地球上所有其他的 shell 脚本系统不一致。当然。感谢像 Shay 这样的 StackOverflow 用户,帮助我们这些普通人理解 Powershell!
  • Resolve-Path 的缺点是它只能解析实际存在的路径。
  • 啊。因此,要全局或扩展您计划创建的路径,您不能使用它。
  • 如果我们想解析一个还不存在的路径,我们可以使用 [System.IO.Path]::Combine((Get-Location), $relativePath)。
【解决方案2】:

根据GetFullPath 的文档,它使用当前工作目录来解析绝对路径。 powershell当前工作目录与当前位置不一样:

PS C:\> [System.IO.Directory]::GetCurrentDirectory()
C:\Documents and Settings\user
PS C:\> get-location

Path
----
C:\

我想你可以使用 SetCurrentDirectory 让它们匹配:

PS C:\> [System.IO.Directory]::SetCurrentDirectory($(get-location))
PS C:\> [System.IO.Path]::GetFullPath(".\foo.txt")
C:\foo.txt

【讨论】:

  • 我有我的提示功能这样做,更新当前的工作目录。
  • 这仅在当前位置在文件系统中时才有效。首先检查 $PWD.Provider.Name。
  • 不检查提供者名称的正确方法:[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath
猜你喜欢
  • 2019-01-27
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
相关资源
最近更新 更多