我想知道是否存在使用驱动器号解析路径的通用方法(例如 X:\foo\bar.txt) 进入其等效的 UNC 路径,该路径可能是以下之一:

  • X:\foo\bar.txt 如果 X: 是一个真正的驱动器(即硬盘、U 盘等)
  • \\server\share\foo\bar.txt 如果 X: 是安装在的网络驱动器 \\server\share
  • C:\xyz\foo\bar.txt 如果 X: 是一个结果 SUBST 命令映射 X:C:\xyz

我知道有一些部分解决方案可以:

  1. 解析网络驱动器(例如,参见 问题 556649 这依赖于 WNetGetUniversalName)

  2. 解决 SUBST 驱动器盘符(参见 QueryDosDevice 它按预期工作,但不会返回本地驱动器或网络驱动器等内容的 UNC 路径)。

我是否缺少一些在 Win32 中实现此驱动器号解析的直接方法?或者我真的必须把两者都搞乱吗 WNetGetUniversalNameQueryDosDevice 得到我需要的东西?

有帮助吗?

解决方案

是的,您需要独立解析驱动器号。

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!
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top