2009-08-26 57 views
10

我正在編寫構建腳本,並且如果用戶構建腳本的目錄中包含空格,則一切都會崩潰。爲了解決這個問題,我想使用8.3文件名,以便drive:\Documents and setttings\whatever變成drive:\Docume~1\whatever。當前目錄可以通過查詢環境變量%CD%找到。如何使用批處理將工作目錄轉換爲8.3短文件名?

如何將%CD%轉換爲短文件路徑?

回答

19
for %f in ("%cd%") do @echo %~sf 

編輯:不要忘記使用%%如果您在批處理文件中使用它。這樣

for %%f in ("%cd%") do @echo %%~sf 

在我的機器:

C:\Users\preet>cd "\Program Files" 
C:\Program Files>for %f in ("%cd%") do @echo %~sf 
C:\PROGRA~1 

其他選項:

另外,FOR變量參照的替換已被增強。 您現在可以使用以下可選語法:

%~I   - expands %I removing any surrounding quotes (") 
    %~fI  - expands %I to a fully qualified path name 
    %~dI  - expands %I to a drive letter only 
    %~pI  - expands %I to a path only 
    %~nI  - expands %I to a file name only 
    %~xI  - expands %I to a file extension only 
    %~sI  - expanded path contains short names only 
    %~aI  - expands %I to file attributes of file 
    %~tI  - expands %I to date/time of file 
    %~zI  - expands %I to size of file 
    %~$PATH:I - searches the directories listed in the PATH 
        environment variable and expands %I to the 
        fully qualified name of the first one found. 
        If the environment variable name is not 
        defined or the file is not found by the 
        search, then this modifier expands to the 
        empty string 

The modifiers can be combined to get compound results: 

    %~dpI  - expands %I to a drive letter and path only 
    %~nxI  - expands %I to a file name and extension only 
    %~fsI  - expands %I to a full path name with short names only 
    %~dp$PATH:I - searches the directories listed in the PATH 
        environment variable for %I and expands to the 
        drive letter and path of the first one found. 
    %~ftzaI  - expands %I to a DIR like output line 
+1

正在尋找這個我自己 - 你會很驚訝爲'for'和命令提示符googling是多麼困難。如果在批處理文件中,則將%s轉義爲%%。 – Will 2009-08-26 10:12:25

+1

我得到這個作爲錯誤消息:此時cd〜sf是意外的。 – Geo 2009-08-26 10:12:25

+0

歡呼聲。我一直忘記這樣做。 – 2009-08-26 10:17:07

-3

更好:在所有路徑周圍使用引號字符(")。

+0

這很難解釋,但這不是一個選項。 – Geo 2009-08-26 10:11:14

+1

不回答OP的問題,並不能解釋爲什麼在它工作的情況下這更好,並不總是有效。 – 2013-12-16 18:27:20

相關問題