How to Check if a Network Share is Accessible in Batch Script
In a distributed environment, many scripts rely on network shares for backups, deployments, or log storage. However, network drives are brittle: they can disconnect due to Wi-Fi drops, server reboots, or changes in permissions. If your script tries to write to a disconnected share, it can hang for minutes or crash entirely. Proactively checking if a network share is reachable before you start your work is a critical guard for any production-grade script.
This guide will explain several methods for verifying network share availability.
Method 1: The IF EXIST Check (Simplest)
The most straightforward way to check a UNC path (e.g., \\Server\Share) is the standard if exist command. This verifies that the path is reachable and that the current user has at least read permission.
@echo off
setlocal
set "TargetShare=\\192.168.1.50\Backups"
rem --- Check for existence ---
rem --- The trailing backslash is required for reliable UNC path checking ---
if not exist "%TargetShare%\" (
echo [ERROR] Network share %TargetShare% is unreachable.
echo [INFO] Possible causes:
echo - The server is offline or restarting.
echo - VPN is not connected.
echo - You do not have permission to access this share.
echo - The share name has changed or been removed.
endlocal
pause
exit /b 1
)
echo [OK] Share is accessible. Proceeding with backup...
endlocal
pause
You must include a trailing backslash (%TargetShare%\) when checking UNC paths with if exist. Without it, if exist can return incorrect results on some Windows versions, particularly when checking a share root rather than a specific file. The trailing backslash tells Windows to verify the path as a directory.
Limitations of if exist:
- It confirms the share is reachable and readable, but not necessarily writable.
- It can hang for 30+ seconds if the server is completely unreachable (no network route). There is no built-in timeout control.
- It uses the current user's credentials. If the script runs as a different user (e.g., Scheduled Task as
SYSTEM), access may differ.
Method 2: The PUSHD / POPD Validation
The pushd command attempts to temporarily map a network share to a drive letter. If it fails, it returns a non-zero errorlevel. This method is often more reliable than if exist for shares that require authentication, because pushd triggers the full Windows authentication and connection process.
@echo off
setlocal
set "Share=\\NAS01\Documents"
echo [CHECK] Attempting to access %Share%...
rem --- pushd to a UNC path creates a temporary drive mapping ---
rem --- If it fails (offline, access denied, bad path), errorlevel is non-zero ---
pushd "%Share%" >nul 2>&1
if %errorlevel% neq 0 (
echo [ERROR] Cannot access %Share%
echo [INFO] The server may be offline, the share may not exist,
echo or you may not have permission.
endlocal
pause
exit /b 1
)
rem --- If we reach here, we are "inside" the share ---
rem --- The current directory is now a temporary drive letter pointing to the share ---
echo [SUCCESS] Connected to %Share%
echo [INFO] Temporary drive mapping: %CD%
echo.
rem --- Perform your work here ---
echo [AUDIT] Contents:
dir /b
rem --- CRITICAL: Always popd when finished ---
rem --- This releases the temporary drive mapping ---
popd
echo.
echo [INFO] Temporary drive mapping released.
endlocal
pause
Why pushd is more robust:
- It triggers the full SMB connection handshake, including authentication.
- The errorlevel clearly indicates success or failure.
- It creates a usable temporary drive letter, which some tools require (not all tools support UNC paths directly).
popdcleanly releases the mapping when you are done.
Critical rule: Every pushd must have a matching popd. If your script exits early (via goto or exit /b) without calling popd, the temporary drive mapping persists until the command prompt session ends, potentially consuming a drive letter.
Method 3: Separating Server Availability from Share Access
Sometimes you need to distinguish between "the server is completely offline" and "the server is up but the share is missing or access is denied." This requires two separate checks.
@echo off
setlocal
set "Server=FILESVR01"
set "ShareName=SharedData"
set "FullPath=\\%Server%\%ShareName%"
echo [CHECK] Verifying access to %FullPath%...
echo.
rem ===================================
rem Step 1: Is the server reachable?
rem ===================================
echo [STEP 1] Pinging server %Server%...
ping -n 1 -w 2000 %Server% >nul 2>&1
if %errorlevel% neq 0 (
echo [ERROR] Server %Server% is completely unreachable.
echo [INFO] The server may be offline, or there is no network route.
echo [INFO] Check your network connection, VPN, or DNS resolution.
endlocal
pause
exit /b 1
)
echo [OK] Server %Server% is online.
echo.
rem ===================================
rem Step 2: Is the share visible?
rem ===================================
echo [STEP 2] Checking if share "%ShareName%" is visible...
rem --- net view lists shares on a server ---
rem --- findstr /i searches case-insensitively for the share name ---
net view \\%Server% 2>nul | findstr /i /c:"%ShareName%" >nul 2>&1
if %errorlevel% neq 0 (
echo [WARN] Server is online, but share "%ShareName%" is not visible.
echo [INFO] The share may be hidden (ending in $^), removed, or you
echo may not have permission to list shares on this server.
echo [INFO] Attempting direct access anyway...
)
rem ===================================
rem Step 3: Can we actually access it?
rem ===================================
echo [STEP 3] Testing direct access to %FullPath%...
if exist "%FullPath%\" (
echo [OK] Share %FullPath% is accessible.
) else (
echo [ERROR] Cannot access %FullPath%.
echo [INFO] The share exists but access is denied, or the path is invalid.
endlocal
pause
exit /b 1
)
endlocal
pause
Important notes about net view:
net view \\Serverlists visible shares. Shares ending with$(likeAdmin$or custom hidden shares likeData$) are not shown bynet viewbut are still accessible if you know the name and have permission.net viewmay fail entirely if the current user does not have permission to enumerate shares on the server, even though specific shares may be accessible. This is why Step 3 (direct access test) is essential.- If
net viewfails butif existsucceeds, the share is accessible, meaning the user simply cannot list all shares on that server.
Method 4: Checking Write Access
Confirming a share is reachable is not enough if your script needs to write data. A share can be accessible but read-only. This script tests actual write capability.
@echo off
setlocal
set "TargetShare=\\192.168.1.50\Backups"
set "TestFile=%TargetShare%\write_test_%RANDOM%.tmp"
rem --- Step 1: Check if the share is reachable ---
if not exist "%TargetShare%\" (
echo [ERROR] Share %TargetShare% is not accessible.
endlocal
pause
exit /b 1
)
echo [OK] Share is reachable. Testing write access...
rem --- Step 2: Attempt to create a temporary file ---
echo test > "%TestFile%" 2>nul
if not exist "%TestFile%" (
echo [ERROR] Share is reachable but READ-ONLY.
echo [INFO] You do not have write permission to %TargetShare%.
echo [INFO] Contact the server administrator to adjust permissions.
endlocal
pause
exit /b 1
)
rem --- Step 3: Clean up the test file ---
del "%TestFile%" >nul 2>&1
echo [OK] Share is writable. Proceeding...
endlocal
pause
%RANDOM% in the filenameUsing a random number prevents conflicts if multiple instances of the script run simultaneously. Each instance creates a uniquely named test file, avoiding race conditions.
Method 5: Retry Loop with Timeout
Network shares can take several seconds to wake up, especially on NAS devices with spinning disks that enter sleep mode. A single failed check may not mean the share is permanently unavailable. This script retries several times before giving up.
@echo off
setlocal enabledelayedexpansion
set "TargetShare=\\NAS01\Backups"
set "MaxRetries=3"
set "RetryDelay=5"
echo [CHECK] Verifying access to %TargetShare%...
set "Attempt=0"
:RetryLoop
set /a Attempt+=1
if exist "%TargetShare%\" (
echo [OK] Share is accessible (attempt !Attempt!^).
goto :ShareReady
)
if !Attempt! geq %MaxRetries% (
echo [ERROR] Share %TargetShare% is unreachable after %MaxRetries% attempts.
echo [INFO] Each attempt waited %RetryDelay% seconds.
endlocal
pause
exit /b 1
)
echo [WARN] Attempt !Attempt!/%MaxRetries% failed. Retrying in %RetryDelay% seconds...
timeout /t %RetryDelay% /nobreak >nul
goto :RetryLoop
:ShareReady
echo [INFO] Proceeding with operations on %TargetShare%...
endlocal
pause
How to Avoid Common Errors
Wrong Way: Checking Mapped Drive Letters Instead of UNC Paths
Mapped drive letters (Z:, S:, etc.) are per-user and per-session. If your script runs as a Scheduled Task under the SYSTEM account or a different user, the mapped drive will not exist even though the share is perfectly accessible.
rem *** BAD: Z: may not exist for this user/session ***
if exist "Z:\backup.txt" echo OK
Correct Way: Always validate using the full UNC path.
rem *** GOOD: UNC paths work regardless of user session ***
if exist "\\Server\Share\backup.txt" echo OK
Wrong Way: Assuming Ping Success Means Share Access
A server can respond to ping but still deny access to its shares. Ping tests ICMP connectivity at the network layer, it tells you nothing about SMB permissions, share existence, or authentication.
rem *** BAD: server is up, but share might be down/denied ***
ping -n 1 Server >nul && echo Share is ready!
Correct Way: Use ping as a first-level diagnostic (Step 1), then verify actual share access with if exist or pushd (Step 2).
Wrong Way: Missing Trailing Backslash on UNC Paths
Without a trailing backslash, if exist may return incorrect results for share root paths.
rem *** UNRELIABLE - may return false results ***
if exist "\\Server\Share" echo OK
Correct Way:
rem *** RELIABLE - trailing backslash ensures directory check ***
if exist "\\Server\Share\" echo OK
Problem: if exist Hangs on Unreachable Servers
When the server is completely offline (no network route), if exist can hang for 30 seconds or more while Windows waits for the SMB connection to time out. There is no built-in timeout parameter for if exist.
Solution: Ping the server first with a short timeout to quickly eliminate unreachable hosts before attempting the slower if exist check.
rem --- Quick reachability check (2-second timeout) ---
ping -n 1 -w 2000 Server >nul 2>&1
if %errorlevel% neq 0 (
echo Server is offline.
exit /b 1
)
rem --- Now the slower if exist check (server is at least reachable) ---
if exist "\\Server\Share\" echo Share is accessible.
Best Practices and Rules
1. Always Use UNC Paths for Validation
UNC paths (\\Server\Share) work regardless of which user runs the script, whether drive letters are mapped, or how the script is launched. They are the only reliable way to reference network shares in automation.
2. Test the Level of Access You Need
If your script reads files, if exist is sufficient. If your script writes files, test write access by creating and deleting a temporary file. A share can be readable but not writable.
3. Add Retry Logic for Sleeping Devices
NAS devices, servers with spinning disks, and cloud-synced shares may take several seconds to respond on first access. A single failed check should trigger a retry, not an immediate failure.
4. Log Network Failures with Timestamps
Network disconnections are infrastructure events that your network team needs to investigate. Always log the exact time, share path, and failure type.
echo %date% %time% - FAIL - %TargetShare% unreachable >> "%~dp0network_audit.log"
5. Match Every pushd with a popd
If you use pushd to access a share, ensure popd is called in every code path, including error paths and early exits. An unmatched pushd leaves a temporary drive mapping that consumes a drive letter.
6. All Commands Used Are Language-Independent
The commands in this guide (if exist, pushd, popd, ping, net view, echo, del) and UNC path syntax are identical across all Windows display languages. Only the descriptive output text from net view is translated. The share names, server names, and path formats are never affected by localization.
7. Use setlocal / endlocal
Always wrap scripts in setlocal and endlocal to prevent variables from leaking into the parent environment.
Final Thoughts
Verifying network share accessibility is a fundamental health check for any resilient Batch script. The key insight is that there are multiple levels of "accessible", the server can be reachable (ping) without the share being visible (net view), the share can be visible without being accessible (if exist), and the share can be readable without being writable (write test). By checking the specific level your script requires, adding retry logic for transient failures, and always using UNC paths instead of mapped drive letters, you build automation that handles network fluctuations gracefully instead of failing silently or hanging indefinitely.