简体   繁体   中英

Windows 10: How can I determine whether a batch file is being run from network mapped drive

I want to prevent a batch file from being run if it is being run from a network location / mapped drive. Is it possible to know if PWD is a mapped drive / network location?

NOTE: This is different from below SO post. In the below post, user knows drive letter on which he wants to prevent running the batch.

Stop Batch file if its being run from a drive

%~d0 references " drive " on which the executed batch file is stored, ie drive letter and colon on batch file is stored on a storage media (local hard disk, USB memory stick, CD/DVD drive, etc. or a network resource with a drive letter assigned (network drive), or two backslashes on batch file is stored on a network resource and was started using a UNC path.

The command net with parameter use outputs the list of network resources with a drive letter assigned which can be searched for the drive letter of the currently executed batch file.

@echo off
if "%~d0" == "\\" (
    echo Batch file is started using UNC path "%~dp0".
    goto :EOF
)
%SystemRoot%\System32\net.exe use | %SystemRoot%\System32\findstr.exe /I /L /C:" %~d0 " >nul
if not errorlevel 1 (
    echo Batch file is started from network drive %~d0.
    goto :EOF
)
echo Okay running batch file from drive %~d0.

Note: The search string can be also just %~d0 instead of " %~d0 " . The additional spaces requiring the quotes just make sure to find a line with drive letter and colon in second column of net use output.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • call /? ... explains modifier ~d on referencing an argument of a batch file like argument 0 which is always the currently processed batch file.
  • echo /?
  • goto /?
  • if /?
  • net /? and net use /?

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM