powershellbatch-filecmd

CD command in batch file does not work in PowerShell


Here is my batch file:

CD c:/
PAUSE

When run in Windows PowerShell, I get this output:

PS C:\some\path\here> .\myscript.bat

C:\some\path\here>CD c:/

c:\>PAUSE
Press any key to continue . . .
PS C:\some\path\here>

After the program terminates, I'm back where I started!

Meanwhile, when run in cmd:

C:\some\path\here>.\myscript.bat

C:\some\path\here>CD c:/

c:\>PAUSE
Press any key to continue . . .

c:\>

I get the behavior I want, where I remain in the C:\ directory after the program ends.

Why is this the case, and how can I get this behavior in PowerShell too?


Solution


  • [1] However, PowerShell by default scopes its shell variables (and other definitions, such as functions) defined in a script to that script. Shell variables (e.g. $foo) are PowerShell-specific variables that are distinct from environment variables (which in PowerShell are referenced with prefix $env:); modifying the latter does take effect process-globally (and affects any child processes, which inherit copies of them) and - unlike in batch files - there's no scoping mechanism.
    Note that cmd.exe makes no distinction between shell and environment variables: any variable that is defined is implicitly an environment variable.