2010-11-01 98 views
11

我希望這個小小的powershell一行代碼能夠回顯foo.txt的完整路徑,其中目錄是我的當前目錄。

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

但事實並非如此。它打印...

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

我不在$ home目錄中。它爲什麼在那裏解決?

+2

你應該使用PowerShell中解決路徑。 – x0n 2010-11-02 14:47:28

回答

16

[System.IO.Path]是使用shell進程的當前目錄。你可以用Resolve-Path cmdlet將獲取的絕對路徑:

Resolve-Path .\foo.txt 
+1

這種行爲是不直觀的,並且與地球上其他所有shell腳本系統不一致。當然。謝謝像Shay這樣的StackOverflow用戶,幫助我們瞭解人們對Powershell的理解! – 2012-11-12 12:19:15

+3

「Resolve-Path」的缺點是它只能解析實際存在的路徑。 – herzbube 2013-04-11 15:12:14

+0

啊。因此,爲了填充或擴展您打算創建的路徑,您不能使用它。 – 2016-12-15 19:44:04

10

根據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 
+0

我有我的提示功能做到這一點,更新當前的工作目錄。 – JasonMArcher 2010-11-08 06:52:22

+0

這隻有在當前位置在文件系統中時纔有效。首先檢查$ PWD.Provider.Name。 – 2012-06-28 13:51:29

+0

沒有提供者名稱檢查的正確方式: [環境] :: CurrentDirectory =(Get-Location -PSProvider文件系統).ProviderPath – 2013-04-30 16:38:56

相關問題