Script - How to check if a network path is available and then map it

I would like an screen saver / logon script that checks if a network path is available and then map it to a unit. If it is not available it disconnects/don't connect.

Network path is \192.168.1.1\drive1

Also I need to use username/password to connect to that path.


You can use the exist command to check if the path is valid:

if exist \\192.168.1.1\drive1 net use s: \\192.168.1.1\drive1

If you need to provide credentials (i.e. your current Windows user doesn't have access to that share), add /user:

if exist \\192.168.1.1\drive1 net use s: \\192.168.1.1\drive1 /user:myDomain\myUser myPassword

If there's a chance that the share already exists, and you want to delete it if it's no longer available, add an else clause:

if exist \\192.168.1.1\drive1 (net use s: \\192.168.1.1\drive1) else (net use /delete s:)

And once again, add the /user if you need it.

You can tie this all together in a batch file similar to the following:

@echo off
if exist \\192.168.1.1\drive1 (set shareExists=1) else (set shareExists=0)
if exist y:\ (set driveExists=1) else (set driveExists=0)
if %shareExists%==1 if not %driveExists%==1 (net use y: \\192.168.1.1\drive1)
if %shareExists%==0 if %driveExists%==1 (net use /delete y:)
set driveExists=
set shareExists=

Powershell would make this easy:

If(Test-Path \\192.168.1.1\Drive1)
  {
    net use M: \\192.168.1.1\Drive1 /user:Domain\UserName Password
  }
else {net use M: /delete > nul}