Search code examples
batch-filecmdnet-use

Return users mapped drive letter from network drive remote


I'm trying to find a way to retrieve the users mapped drive letter from a network drive. I've read a few posts here but they all seem to be around mapping/unmapping drives, whereas I simply need to know what drive the user has that network drive mapped to.

From a command prompt I use: Net Use s: for example will give me the name of the networked drive (\servershare\file\sharename\shared), however

Net Use \\servershare\file\sharename\shared

just gives "The command completed successfully", where I need 'S:' returning.

How do I get the drive letter returned for a specific network drive?


Solution

  • A batch file like this will work:

    @FOR /F "tokens=2" %%D IN ('net use ^| find ":" ^| find /I "\\SERVER\SHARE"') DO @ECHO Drive letter is %%D
    

    Notes:

    • Replace ECHO Drive letter is %%D with whatever code you want now that the drive letter is known, possibly a multi-line code block surrounded by ( and ). Replace \\SERVER\SHARE with the share you're looking for.
    • If there's no drive mapped to the share, the statement after DO will never execute. If there's more than one drive mapped to the share, it will execute once for each drive.
    • You could skip the first ^| find ":" pipe if you're sure there won't be any connections without a drive letter (e.g. created with net use \\SERVER\SHARE as opposed to net use S: \\SERVER\SHARE or net use * \\SERVER\SHARE).
    • You could skip the /I switch if you're sure there won't be any connections to the share using different character case.
    • The two @ characters prevent the commands from echoing on the console. An alternative is to begin the batch file with @ECHO OFF'.
    • If you're running this directly on the command line instead of from a batch file, replace the the two %%D with %D.