Windows – Command line: Map network drive

command-line-interfacewindows

How do I write a command line in a .bat or .cmd that maps a network drive? I want the script to first check if the drive-letter is mapped, and if it is delete it and then map the drive.

I only have the mapping-command right now. Please help me fill in the blanks:

REM Check if drive exists, if it does, delete it

@echo off

net use q: /persistent:yes \\localhost\C$\MyFolder

pause

Are there any of the parameters wrong? Any that should be added?

Best Answer

You can test for the existence of a drive or folder by testing if the special file "nul" exists in it, i.e.

REM Test if drive exists

IF EXISTS Q:\NUL GOTO Unmap

GOTO Continue

:Unmap

NET USE Q: /DELETE

:Continue

NET USE Q: /persistent:yes \\localhost\C$\MyFolder

Of course, since you are going to delete it anyway, you could simply delete it and not bother checking for existence first.