pushd not working in a batch file with delayed expansion

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

If you're experiencing issues with pushd not working in a batch file with delayed expansion enabled, it might be due to the way delayed expansion affects the handling of special characters like ! in path names.

To work around this issue, you can temporarily disable delayed expansion before using pushd, and then re-enable it afterward. Here's an example:

batch
@echo off
setlocal enabledelayedexpansion

rem Disable delayed expansion
setlocal disabledelayedexpansion

rem Save the current directory
set "currentDir=%CD%"

rem Enable delayed expansion
setlocal enabledelayedexpansion

rem Use pushd with the desired directory
pushd "C:\Path\To\Directory"

rem Your commands in the desired directory go here

rem Return to the original directory
popd

rem Disable delayed expansion
endlocal

rem Restore the original directory
cd "%currentDir%"

rem Re-enable delayed expansion
endlocal

In this script, delayed expansion is temporarily disabled and re-enabled using setlocal and endlocal commands. The current directory is saved before entering the desired directory with pushd, and then restored afterward using cd.