批处理文件:如何检查 %~dp0 是否是 UNC 网络路径?
batch file: how to check if %~dp0 is a UNC network path?
我已经看到 How to run batch file from network share without "UNC path are not supported" message? - pushd %~dp0
将网络路径安装为驱动器,popd
卸载驱动器,似乎对我有用。
我只想让批处理脚本能够检测脚本的启动位置是本地路径还是 network/UNC 路径。我怎么能那样做?我猜,可以检查路径中的前两个字符是否是反斜杠 \
,但我不知道如何批量进行。
所以,作为某种伪代码,我需要这样的东西:
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
您可以使用 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%
你也可以使用这个:
@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
我已经看到 How to run batch file from network share without "UNC path are not supported" message? - pushd %~dp0
将网络路径安装为驱动器,popd
卸载驱动器,似乎对我有用。
我只想让批处理脚本能够检测脚本的启动位置是本地路径还是 network/UNC 路径。我怎么能那样做?我猜,可以检查路径中的前两个字符是否是反斜杠 \
,但我不知道如何批量进行。
所以,作为某种伪代码,我需要这样的东西:
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
您可以使用 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%
你也可以使用这个:
@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