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.
4 Answers
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= 9Powershell 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} 9It is just simplier to just try to map it using the Windows File explorer or using the net use command. Either it works or it doesn't.
2This is the final code:
function run{ net use If(Test-Path \\192.168.1.1\volume1) { if (((New-Object System.IO.DriveInfo("Y:")).DriveType -ne "NoRootDirectory")) { "already mounted and accessible" } else { net use Y: \\192.168.1.1\volume1 "mounting" } } else { if (((New-Object System.IO.DriveInfo("Y:")).DriveType -ne "NoRootDirectory")) { net use Y: /delete "removing" } } exit 4 } run I use Test-Path \\192.168.1.1\volume1 as suggested to check if the network path is available and ((New-Object System.IO.DriveInfo("Y:")).DriveType -ne "NoRootDirectory") to check if the drive letter exists.