bat脚本在C:\Program Files (x86)使用普通权限运行与使用管理员权限运行获取当前路径的差异

bat脚本在C:\Program Files (x86)使用管理员权限运行获取当前路径不对。

bat脚本如下:

@echo off
set "current_dir=%cd%"
echo Current directory: %current_dir%
set "filepath=%current_dir%\1.txt"
setlocal enabledelayedexpansion

if exist "%filepath%" (
    for /f "usebackq delims=" %%a in ("%filepath%") do (
        echo %%a
    )
) else (
    echo File not found.
)

endlocal

pause

普通权限运行bat脚本:

 管理员权限运行bat脚本:

 所以需要在获取路径之前通过cd /d命令将工作目录切换到C:\Program Files (x86),或者进入当前路径 cd /d %~dp0

@echo off
rem 进入当前路径
cd /d %~dp0
set "current_dir=%cd%"
echo Current directory: %current_dir%
set "filepath=%current_dir%\1.txt"
setlocal enabledelayedexpansion

if exist "%filepath%" (
    for /f "usebackq delims=" %%a in ("%filepath%") do (
        echo %%a
    )
) else (
    echo File not found.
)

endlocal

pause

如果是在C:\Program Files (x86)路径下的bat读取文件内容到另一个文件,路径需要重新赋值到一个新变量(注意=左右两边不能有空格),并且需要两边增加双引号

set aaa="%output_file%" 
不然因为C:\Program Files (x86)路径中间有空格,没加""会出错。
@echo on
setlocal enabledelayedexpansion
rem 进入当前路径
cd /d %~dp0
set "current_dir=%cd%"
echo Current directory: %current_dir%
set "filepath=%current_dir%\1.txt"
set "output_file=%~dp0\11.txt"
rem 注意=左右两边不能有空格
set aaa="%output_file%"

if exist "%filepath%" (
    for /f "usebackq delims=" %%a in ("%filepath%") do (
        echo %%a
    )
) else (
    echo File not found.
)

pause
for /f "usebackq delims=" %%a in ("%filepath%") do (
    set "line=%%a"
    echo !line!>> %aaa%
)

endlocal

pause

 

posted @ 2023-05-31 15:12  log9527  阅读(213)  评论(0编辑  收藏  举报