use cmd.exe to change directory and run command in that directory
Asked Answered
G

3

37

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.

Gearard answered 11/5, 2012 at 13:44 Comment(0)
D
56

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"
Dander answered 11/5, 2012 at 14:39 Comment(0)
F
7

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
Fail answered 11/5, 2012 at 14:0 Comment(5)
& and && both allow multiple commands, but for && runs the seconds only if first is successfulGearard
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 meFail
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:Gearard
if you are already at the command prompt get rid of the "cmd /c "Fail
it's got to work in c# app too so I'm using that to run the cmd /cGearard
K
4

You want quotes around that command line:

cmd /c "cd c:/ & dir"

Kumquat answered 11/5, 2012 at 13:46 Comment(3)
that still returns dir from the P driveGearard
This answer adds something useful. You need the quotes around your command, else each action will be executed independently. As Stagg says, you might want to add the /d option to change drives, thoughShoebill
The quotes tip here is what solved my issueHorripilate

© 2022 - 2024 — McMap. All rights reserved.