Leo Nix
Leo Nix

Reputation: 2105

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.

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.

Upvotes: 15

Views: 12036

Answers (3)

Leo Nix
Leo Nix

Reputation: 2105

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

Upvotes: 4

kodybrown
kodybrown

Reputation: 2593

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.

Upvotes: 4

aphoria
aphoria

Reputation: 20189

You can use . to represent the current diretory.

Try this:

PUSHD .

REM The rest of you script

POPD

Upvotes: 19

Related Questions