33

All I want to do is:

  1. change to specific directory of a different drive
  2. run a command in that directory e.g. dir

I need to do this in one line using cmd.exe starting from a different drive

I would do this like this:

c:
cd temp
dir 

so in one statement so far I have:

cmd /c c: & cd\temp & dir

But this just gives me dir for the P: directory which I start from. How can I get dir returned from c:\temp?

I can't run a batch file and it must be in a one-line statement.

Stagg
  • 2,660
  • 5
  • 34
  • 32

3 Answers3

51

You may want to invoke CD with the /d option, thus not only changing the current directory on drive c: but also going there (in case you are not already on that drive).

 cmd /c "cd /d c:\temp && dir"
Christian.K
  • 47,778
  • 10
  • 99
  • 143
5

you use && or & to separate multiple commands

if the cmd window is already opened and running from command line

 c: && cd\temp && dir

or

cmd /c && c: && cd\temp && dir
Gratzy
  • 9,164
  • 4
  • 30
  • 45
  • & and && both allow multiple commands, but for && runs the seconds only if first is successful – Stagg May 11 '12 at 14:23
  • Are you simply running this from a command line or are you spawning the cmd.exe process from some other app? Because both & and && worked for me – Gratzy May 11 '12 at 14:25
  • I'm testing on the command line but going to run it in c# app. Note that I also need to change to a different drive as well e.g starting drive is P: and the cmd line needs to change to C: – Stagg May 11 '12 at 14:33
  • if you are already at the command prompt get rid of the "cmd /c " – Gratzy May 11 '12 at 14:38
  • it's got to work in c# app too so I'm using that to run the cmd /c – Stagg May 11 '12 at 14:39
2

You want quotes around that command line:

cmd /c "cd c:/ & dir"

Kilian Foth
  • 13,904
  • 5
  • 39
  • 57