Batch check if mapped network drive exists

Another possible way could be:

net use Z:
if %errorlevel% EQU 0 net use Z: /delete
net use Z: \\path

You can check whether the drive is mounted by IF EXIST Z:\. This should work:

if exist z:\ (
    net use z: /delete
)
net use z: \\path

I use the following scriptbit to unmap all drives:

:: First unmap all network drives
FOR /F "tokens=1,2,3" %%G IN ('net use^| Find "\\"') DO (
  ECHO.Unmapping %%I from drive letter %%H
  NET USE %%H /D > NUL
)

What does it do? Let's split this up

FOR /F "tokens=1,2,3" %%G IN () DO ()--> will iterate over the set defined between () and the first, second and third word (any whitespace is used as separator) will become available as %%G, %%H and %%I respectively.

('...') will run a command ... and pass the result(s) to the FOR loop

net use will output something like this:

New connections will be remembered.


Status       Local     Remote                    Network

-------------------------------------------------------------------------------
OK           M:        \\diskstation\music       Microsoft Windows Network
OK           P:        \\diskstation\home        Microsoft Windows Network
OK           V:        \\diskstation\video       Microsoft Windows Network
OK           X:        \\diskstation\photo       Microsoft Windows Network
The command completed successfully.

This output is then piped to Find.exe (the windows equivalent to grep) which looks for "\\".

The pipe symbol | is escaped using ^ so cmd does not execute it directly. The output will then be:

OK           M:        \\diskstation\music       Microsoft Windows Network
OK           P:        \\diskstation\home        Microsoft Windows Network
OK           V:        \\diskstation\video       Microsoft Windows Network
OK           X:        \\diskstation\photo       Microsoft Windows Network

NET USE /D will delete the drive mapping for the selected mapping