Batch file 将UNC源映射为驱动器
当我从.CMD文件中运行脚本时,%~dp0将获得当前/工作目录。它知道UNC路径。但是,我在三个闪存驱动器、五个不同的便携式驱动器和三个不同的文件服务器上有几个脚本。我希望能够编写一个脚本,在所有脚本上运行Batch file 将UNC源映射为驱动器,batch-file,cmd,Batch File,Cmd,当我从.CMD文件中运行脚本时,%~dp0将获得当前/工作目录。它知道UNC路径。但是,我在三个闪存驱动器、五个不同的便携式驱动器和三个不同的文件服务器上有几个脚本。我希望能够编写一个脚本,在所有脚本上运行 如何使用脚本查看“%~dp0”,确定是否在UNC源上,如果源是UNC,则映射驱动器,否则只需运行?您可以使用以下命令检查驱动器是否映射- net use %~d0 2>nul >nul || echo drive not mapped & goto :run 2>nul
如何使用脚本查看“%~dp0”,确定是否在UNC源上,如果源是UNC,则映射驱动器,否则只需运行?您可以使用以下命令检查驱动器是否映射-
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
(不太可能全部映射-您可以添加/删除字母)检查它们是否已映射。如果没有,请将路径映射到该驱动器号,然后继续执行脚本
@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