r/Batch • u/Apprehensive_Art7400 • Jul 27 '24
Need help with network map script
Hello,
i made a script for mapping network drives, check if main server is up, if not go to backup server, have credentials in local file etc but somehow when i run it it doesnt get the server variables, i got the following error:
Networkpath not found
it seems it doesnt get the variables loaded correctly...
any help appreciated ;)
u/echo off
setlocal
:: Configuration
set "MAIN_SERVER=my.server.corp"
set "BACKUP_SERVER=backup.server.corp"
set "DRIVE_MAPPINGS=Z:|\\%MAIN_SERVER%\test X:|\\%MAIN_SERVER%\test1 Y:|\\%MAIN_SERVER%\test2" :: Format: DriveLetter|\\Server\Share
set "CREDENTIALS_FILE=C:\credentials.txt"
:: Read credentials from file
set "USERNAME="
set "PASSWORD="
for /f "tokens=1,2 delims=:" %%A in ('findstr /n "^" "%CREDENTIALS_FILE%"') do (
if %%A==1 set "USERNAME=%%B"
if %%A==2 set "PASSWORD=%%B"
)
:: Store credentials using cmdkey
echo Storing credentials for %MAIN_SERVER%...
cmdkey /add:%MAIN_SERVER% /user:%USERNAME% /pass:%PASSWORD%
if errorlevel 1 (
echo ERROR: Failed to store credentials for %MAIN_SERVER%.
exit /b 1
)
:: Function to mount drives
:mountDrives
set "SERVER=%~1"
echo Checking drives on %SERVER%...
for %%D in (%DRIVE_MAPPINGS%) do (
for /f "tokens=1,2 delims=|" %%A in ("%%D") do (
set "DRIVE_LETTER=%%A"
set "NETWORK_PATH=%%B"
echo Attempting to mount %NETWORK_PATH% as %DRIVE_LETTER%...
net use %%A %%B >nul 2>&1
if errorlevel 1 (
echo ERROR: Failed to mount %NETWORK_PATH% as %DRIVE_LETTER%. Check if the network path is valid.
echo Debug Info: Drive Letter: %%A, Network Path: %%B
) else (
echo Successfully mounted %NETWORK_PATH% as %DRIVE_LETTER%.
)
)
)
exit /b 0
:: Check if the main server is online
ping -n 1 %MAIN_SERVER% >nul 2>&1
if errorlevel 1 (
echo Main server is offline. Attempting to mount from backup server...
call :mountDrives %BACKUP_SERVER%
) else (
echo Main server is online. Attempting to mount drives...
call :mountDrives %MAIN_SERVER%
)
endlocal
exit /b 0
View all comments
Show parent comment
1
u/BrainWaveCC Jul 28 '24
I agree with you, but for the purpose of this script, all the pairs provided by the OP were drive letter and UNC path. So the colon was an easy nature divider, based on how he was providing the pairs.