【问题标题】:CMD line to tell if a file/path is local or remote?CMD 行来判断文件/路径是本地的还是远程的?
【发布时间】:2011-06-27 17:39:44
【问题描述】:

通过 NT shell 脚本,我需要能够判断目标路径是在本地驱动器上(如 C:\D:\)还是在远程/映射驱动器上(\\UNC\path 或映射驱动器像Z:)这样的信...有什么建议吗?

【问题讨论】:

    标签: batch-file cmd


    【解决方案1】:
    @echo off
    goto main
    
    :isremote
    setlocal
    set _isremote=0
    if "%~d1"=="\\" (set _isremote=1) else (
        (>nul 2>&1 net use "%~d1") && set _isremote=1
    )
    endlocal&set isremote=%_isremote%&goto :EOF
    
    :test
    call :isremote "%~1"
    echo %isremote% == %~1
    @goto :EOF
    
    :main
    call :test c:
    call :test c:\
    call :test c:\windows
    call :test \\foo
    call :test \\foo\
    call :test \\foo\bar
    call :test \\foo\bar\baz
    call :test z:
    call :test z:\
    call :test z:\temp
    

    在我的系统上,z: 是我得到的映射驱动器:

    0 == c:
    0 == c:\
    0 == c:\windows
    1 == \\foo
    1 == \\foo\
    1 == \\foo\bar
    1 == \\foo\bar\baz
    1 == z:
    1 == z:\
    1 == z:\temp
    

    注意:NT6+ 上的 UNC 符号链接可能会失败

    【讨论】:

    • 哦,巧妙地使用net use %~d1 加上&&——比我循环遍历net use 结果要好得多!
    【解决方案2】:

    以下是我想出的。目标文件/路径作为参数 %1 传递。

    set REMOTE=0
    set TEST=%~f1
    if "%TEST:~0,2%"=="\\" (
        echo *** target is a remote UNC path
        set REMOTE=1
    ) else (
        for /f "skip=6 tokens=2" %%d in ('net use') do (
            if /i "%TEST:~0,2%"=="%%d" (
                echo *** target is a remote mapped drive
                set REMOTE=1
            )
        )
    )
    if %REMOTE%==0 echo *** target is a local file/directory
    

    【讨论】:

    • \\?\C: 以两个反斜杠开头......并且很可能是本地路径。实际上,这就是如何打破 Win32 API 中路径长度的 260 个字符的障碍。
    • @STATUS_ACCESS_DENIED:虽然这是真的,但 %~dI 的 cmd.exe 内置扩展器记录为“仅将 %I 扩展为驱动器号”对于“\\?\ C:" 因为它会返回 "\\"
    【解决方案3】:

    最好的办法是使用这样的东西:

    fsutil fsinfo drivetype X:
    

    但是,由于 fsutil 的输出,相应的代码可能取决于语言。如果这不是问题,您最好标记化并使用 fsutil 的输出。

    【讨论】:

      【解决方案4】:

      Ruby 中的基本识别脚本,不支持映射驱动程序。

      where_placed.rb:

      path = ARGV[0]
      if path.start_with? "\\"
        puts "remote"
      else
        puts "local"
      end
      

      > ruby where_placed.rb "C:\file.dat>“本地”

      > ruby where_placed.rb "\\REMOTEMACHINE\file.dat>“远程”

      【讨论】:

      • 映射驱动器呢,它们是远程的,但不以 \\ 开头。为什么 ruby​​,如果检查 \\ 就足够了,您可以在批处理文件中进行...
      • 我喜欢 Ruby,可惜它对于这个脚本来说不够便携,它必须是“纯”CMD shell。
      • 以 `\\?` 开头并且不是远程的本地路径呢?
      • 我说这是非常基本的脚本 :) 我不知道如何在纯 CMD 脚本中执行此操作,因为我对 windows 及其 shell 不感兴趣。
      猜你喜欢
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      • 2021-06-22
      • 1970-01-01
      相关资源
      最近更新 更多