Windows batch file starting directory when 'run as admin'

前端 未结 8 1675
情书的邮戳
情书的邮戳 2020-12-12 20:02

I have a batch file which is in a directory and must be run from there as well because it updates files within this directory.
This works perfectly fine, except when t

相关标签:
8条回答
  • 2020-12-12 20:40

    You can CD directly from the file name by adding the parent (not tested in windows 8.x, but has worked "forever" as far as I can remember).

    CD %FILENAME%\..
    

    and CD will change drives as well using /D, which is shown above but not explicitly mentioned so might be missed. CD /D %FILENAME%\..

    (FOR /? IF /? SET /? CALL /? GOTO /? all provide highly useful reading if you use cmd.exe, I reread them once in a while.)

    0 讨论(0)
  • 2020-12-12 20:41

    A working solution here:

    http://www.vistax64.com/vista-general/79849-run-administrator-changes-default-directory.html

    FOR /F %%I IN ("%0") DO SET BATDIR=%%~dpI

    ECHO The batch file is located in directory %BATDIR%

    0 讨论(0)
  • 2020-12-12 20:44

    This should solve your problem by setting the working directory for the batch file back to the current directory:

    Include these two lines at the top of your .bat script:

    @setlocal enableextensions
    @cd /d "%~dp0"
    

    Found at: http://www.codeproject.com/Tips/119828/Running-a-bat-file-as-administrator-Correcting-cur

    0 讨论(0)
  • 2020-12-12 20:45

    Better than cd is pushd which will

    • change drive letter if starting from D:\...
    • assign a drive letter if on a UNC network path

    So pushd %~dp0 is good.

    Good practice is then to call popd when done.

    0 讨论(0)
  • 2020-12-12 20:48

    @setlocal enableextensions

    @cd /d "%~dp0"

    0 讨论(0)
  • 2020-12-12 20:51

    To fix this problem, include these two lines at the top of your .bat script:

    @setlocal enableextensions
    @cd /d "%~dp0"
    
    0 讨论(0)
提交回复
热议问题