当我从.CMD文件中运行脚本时,%~dp0将获取当前/工作目录。它了解UNC路径。但是,我在三个闪存驱动器,五个不同的便携式驱动器和三个不同的文件服务器上有几个脚本。我希望能够编写一个脚本来运行它们。
如何使用脚本查看“%~dp0”,确定是否在UNC源上,如果源是UNC则映射驱动器,否则只运行?
答案 0 :(得分:0)
您可以使用以下内容检查驱动器是否已映射 -
net use %~d0 2>nul >nul || echo drive not mapped & goto :run
2>nul >nul
将stdout和stderr重定向到nul。
||
之后的命令只有在net use命令设置错误级别时才会运行。
如果要检查驱动器是否在远程服务器上,但未映射,请映射驱动器 -
if "%~d0"=="\\" for /f %%D in (R S T U V W X Y Z) do if not exist %%D:\ (
net use %%D: %~dp0 >nul
set path=%%D:
goto :run
)
:run
如果远程运行脚本, %~d0
将等于\\
,但路径尚未映射。
循环遍历R S T U V W X Y Z
(不太可能全部映射 - 您可以添加/删除字母),检查 是否已经映射。如果不是,请将路径映射到该驱动器号并继续使用脚本
答案 1 :(得分:0)
@echo off
setlocal enableextensions
( call :ensureMappedRun %* )|| exit /b
rem This line is reached when :ensureMappedRun finishes with errorlevel=0
rem meaning the batch file is not being executed from a UNC path
echo running "%~f0" %*
pause
endlocal
exit /b 0
:ensureMappedRun
rem test if current context is "drive:...."
echo %~f0 | findstr /r /i /b /c:"[a-z]:" >nul 2>nul
if not errorlevel 1 exit /b 0
rem Running from UNC path. Map to drive letter
pushd "\\%~p0"
if errorlevel 1 (
echo ERROR : UNC path not accesible or no drive letters available
pause
exit
)
rem Restart the current batch file from the new drive\path
call "%cd%\%~nx0" %*
rem Clean the drive assignment
popd
rem And return, signaling the batch has been run redirected
exit /b 1