6

I need to changed directory using batch file in PowerShell.

Let's say the batch file named go.bat has the two lines of code. And I'm in q: directory.

   c:
   cd c:\abc\def

When I run go.bat, I'm still in q:

3
  • What exactly is not working? Are you running a .bat file from PowerShell and expecting it to change the PWD of the PowerShell host?
    – Rynant
    Mar 7, 2012 at 19:23
  • 2
    When you run a .bat file, the batch file runs in a child cmd.exe process. It won't change the directory of the parent PowerShell process.
    – Rynant
    Mar 7, 2012 at 22:03
  • A .ps1 file is a PowerShell script, not what is commonly known as a batch (or command file) which is interpreted by command.exe and has a .bat or .cmd file extension.
    – martineau
    Mar 7, 2012 at 22:13

6 Answers 6

5

While I agree that what you're doing should work, you can always try the Powershell cmdlet "set-location". It basically works the same way:

set-location c:\abc\def
1
  • 1
    @set-location works but it doesn't work when I run the command in batch file.
    – prosseek
    Mar 7, 2012 at 21:58
5

When you run a batch file, PowerShell creates a CMD.EXE process to run the file. If you change the working directory inside the CMD.EXE process, it won't affect the current working directory of PowerShell. This is by design.

1
  • 1
    Is there any way using PowerShell to change this behaviour, to execute the bat file within the active CMD.EXE process?
    – PJussel
    Aug 29, 2016 at 5:30
3

Just encountered this problem, I wanted to have a script for jumping to a directory which works in Powershell and CMD.

I could solve it by creating a script with the same name, one is a powershell script and the other a bat file:

Powershell

Set-Location C:\abc\def

Batch

cd C:\abc\def

Let us say the script is just called "def". If I type def in Powershell, it will run the ps1 version, if I type it in cmd, it will run the bat. You have to have duplicate files but you get to use the same named command between shells.

1
  • This was what I had to do. The cd nor cd /D command does not work from a bat in PS. Nor can we call Set-Location in PS from a batch. Jul 15, 2021 at 14:42
2

Have you checked that C:\abc\def exists?

On my machine starting from the E: drive

  • C:
  • cd C:\windows\system32

works perfectly fine

0
2

Try:

   cd /D c:\abc\def

Use the /D switch to change current drive in addition to changing current directory for a drive -- although I'm not sure why what you tried isn't working...

If the folder doesn't exist you'll get an error message:

The system cannot find the path specified.

You can view some help on the cd command by typing cd /?.

0
0

In batch you can’t change to UNC path for example:

cd \192.169.10.15\work_dir

In that case powershell can do it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .