這是批處理,將驅動器號轉換爲UNC路徑或反向消隱路徑。不保證它可以工作。使用
例子:script.cmd echo Z: Y: W:
@echo off
:: u is a variable containing all arguments of the current command line
set u=%*
:: enabledelayedexpansion: exclamation marks behave like percentage signs and enable
:: setting variables inside a loop
setlocal enabledelayedexpansion
:: parsing result of command subst
:: format: I: => C:\foo\bar
:: variable %G will contain I: and variable H will contain C:\foo\bar
for /f "tokens=1* delims==> " %%G IN ('subst') do (
set drive=%%G
:: removing extra space
set drive=!drive:~0,2!
:: expanding H to a short path in order not to break the resulting command line
set subst=%%~sfH
:: replacing command line.
call set u=%%u:!drive!=!subst!%%
)
:: parsing result of command net use | findstr \\ ; this command is not easily tokenized because not always well-formatted
:: testing whether token 2 is a drive letter or a network path.
for /f "tokens=1,2,3 delims= " %%G IN ('net use ^| findstr \\') do (
set tok2=%%H
if "!tok2:~0,2!" == "\\" (
set drive=%%G
set subst=%%H
) else (
set drive=%%H
set subst=%%I
)
:: replacing command line.
call set u=%%u:!drive!=!subst!%%
)
call !u!
啊,是的,去了CMD的方式是我最初拒絕了一個解決方案。我真的試圖找到一個Win32 API,它可以做到這一點。顯然,您的解決方案應該適用於在批處理/腳本環境中嘗試做同樣事情的人。非常感謝您的想法;這是我重新發現一些CMD技巧的場合。 – 2011-01-13 04:41:17
這個腳本很棒。只有一個錯誤 - 它不支持替代驅動路徑中的空格。要修復,請將第一個for循環改爲: ... tokens = 1,2 ... 至 ... tokens = 1 * ... – 2011-04-11 13:52:57
@MrBungle:謝謝!我不知道'tokens = 1 *',會調查。你確定它不是'1,2 *'嗎? – Benoit 2011-04-11 18:25:32