解决Windows驱动器号到一个路径(子网和网络)
问题描述:
我想知道是否有一种通用的方法使用驱动器号(例如X:\foo\bar.txt
)将路径解析到其等效的UNC路径中,该路径可能是以下之一:解决Windows驱动器号到一个路径(子网和网络)
-
X:\foo\bar.txt
如果X:
是一个真正的驱动器(即硬盘,USB棒等) -
\\server\share\foo\bar.txt
如果X:
是安装在\\server\share
-
C:\xyz\foo\bar.txt
X:
如果网络驱动器是一个012的结果命令映射X:
到C:\xyz
我知道有部分的解决方案,这将:
解决网络驱动器(例如见question 556649其依赖于
WNetGetUniversalName
)解决该
SUBST
驱动器号(请参阅QueryDosDevice
,它按预期方式工作,但不返回本地驱动器或网络驱动器等事物的UNC路径)。
我是否错过了在Win32中实现此驱动器号解析的一些直接方法?或者我真的必须混淆WNetGetUniversalName
和QueryDosDevice
才能获得我需要的东西?
答
是的,您需要独立解决驱动器号。
WNetGetUniversalName()
接近,但只适用于映射到实际UNC股份的驱动器号,但并非总是如此。没有一个API函数可以为您完成所有的工作。
答
这是批处理,将驱动器号转换为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