为什么PowerShell从$ home而不是当前目录解析路径?

Jos*_*del 15 powershell

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

[System.IO.Path]::GetFullPath(".\foo.txt")
Run Code Online (Sandbox Code Playgroud)

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

C:\Documents and Settings\Administrator\foo.txt
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*evy 18

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

Resolve-Path .\foo.txt
Run Code Online (Sandbox Code Playgroud)

  • 这种行为是不直观的,并且与地球上的每个其他shell脚本系统不一致.当然.感谢StackOverflow用户喜欢Shay,帮助我们了解人类对Powershell的理解! (3认同)
  • "Resolve-Path"的缺点是它只能解析实际存在的路径. (3认同)

zda*_*dan 12

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

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

Path
----
C:\
Run Code Online (Sandbox Code Playgroud)

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

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

  • 不检查提供者名称的正确方法:[Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath (2认同)