5

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:

  • 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 '12 at 19:23
  • 1
    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 '12 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 '12 at 22:13
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
  • @set-location works but it doesn't work when I run the command in batch file. – prosseek Mar 7 '12 at 21:58
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

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 /?.

2

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.

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

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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.