3

I have seen How to run batch file from network share without "UNC path are not supported" message? - and the pushd %~dp0 to mount the network path as a drive, and popd to unmount the drive, seems to work for me.

I'd just like to make the batch script capable of detecting whether the location the script is started from is a local, or a network/UNC path. How could I do that? I'd guess, one could check if the first two characters in the path are backslashes \\, but I have no idea how to do it in batch.

So, as somewhat of a pseudocode, I'd need something like:

call :IsUncPath %~dp0 is_unc_path

if %is_unc_path% == 1 (
  echo "Mounting UNC path as local drive"
  REM @pushd %~dp0
)

echo "Script does whatever here..."

if %is_unc_path% == 1 (
  echo "Unmounting local drive for UNC path"
  REM @popd
)

pause
:: "force execution to quit at the end of the "main" logic" http://steve-jansen.github.io/guides/windows-batch-scripting/part-7-functions.html
EXIT /B %ERRORLEVEL%

:IsUncPath
echo The value of parameter 1 is %~1
:: NB: there must not be spaces around the assignment!
set "%~2=1"
EXIT /B 0
sdbbs
  • 4,270
  • 5
  • 32
  • 87
  • Well, why do you want to do that? you could do `pushd`/`popd` anyway for all paths since local paths are kept unchanged and remote paths are mounted to a local drive... – aschipfl Dec 06 '19 at 12:03

2 Answers2

2

You could use the errorlevel of net use <drive letter>.

call :isUncPath C:
if %errorlevel% == 0 echo C: is on UNC
exit /b

:IsUncPath
::: param1 - drive letter with colon, ex Y:
::: @return exitcode 0 - drive is network mapped
net use %~1 >nul 2>&1
EXIT /B %errorlevel%
jeb
  • 78,592
  • 17
  • 171
  • 225
  • Many thanks, that looks good! However, I don't really know how to read the return error code from a batch function - would you mind how I would read the return error status, and put it into a variable? (and what value should I check for, to determine this is indeed a network path? is it `returncode != 0`?) – sdbbs Dec 06 '19 at 10:49
  • 1
    @sdbbs I edited my answer to show the use of an errorlevel – jeb Dec 06 '19 at 18:31
1

You can also use this:

@echo off
call :chkunc
if %errorlevel% equ 0 echo "%~dp0" is on UNC 
:: rest of your script
exit /b
:chkunc
set "testpath=%~dp0"
if "%testpath:~0,2%"=="\\" exit /b 0
exit /b 1
Wasif
  • 14,755
  • 3
  • 14
  • 34