简体   繁体   中英

Windows Command: how do I push current directory using chdir for popping later?

Context/Objective:

In windows 7, I'm developing a batch script using regular windows commands. Within this batch, I need to save the current directory first thing so it can be restored when the script finishes running.

What I have tried so for:

I've attempted to use commands of chdir, pushd and popd to make it work.

  • Try 1:

    PUSHD CHDIR

    REM main script body

    POPD

    Result: error on PUSHD line "the system cannot find the path specified"

  • Try 2:

    SET curdir=CHDIR

    PUSHD %curdir%

    REM main script body

    POPD

    Result: same error on PUSHD line "the system cannot find the path specified"

  • Other tries: Also googling didn't yield any satisfactory results.

The Questions:

Can I make it work using these commands? Or is there another set of commands that I need to use?

Note:I'm looking for a solution using windows native commands only, third party tools or powershell is not an option.

You can use . to represent the current diretory.

Try this:

PUSHD .

REM The rest of you script

POPD

Your problem is that you need to use the CD command (instead of CHDIR) and don't forget to wrap it in %'s.. It is common to think they are they same, but they do differ, slightly, in this way.

Try the following example in a batch file:

@echo off

echo Initial directory set to:
cd "%UserProfile%\Desktop"
echo   `%cd%`
echo.

pushd %CD%

echo Changing to %AppData%
REM main script body
cd /D %AppData%
echo   `%cd%`
echo.

echo Changing to %LocalAppData%
cd /D %LocalAppData%
echo   `%cd%`
echo.

echo.
echo About to POPD
pause
POPD
echo   `%cd%`
echo.

I should note the @aphoria's answer is just as valid.

Working solutions by both @aphoria and @wasatchwizard. Wish I could mark both as answers. Thank you both!

I'm consolidating them into one for those who will run into the same questions.

Option 1:

PUSHD .
REM main scripts body
POPD

Option 2:

PUSHD %cd%
REM main scripts body
POPD

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM