How do I set an executable's working directory via the command line, prior to executing it?

110,353

Solution 1

To explicitly set the working directory, a PowerShell solution would be to use the Start-Process cmdlet with the -WorkingDirectory parameter.

Start-Process -FilePath notepad.exe -WorkingDirectory c:\temp

Using the alias start, positional parameter, and partial parameter name this could be written as:

start notepad.exe -wo c:\temp

CMD also has a START command. For this, use the /D parameter to specify the working directory:

START /D c:\temp notepad.exe

Solution 2

The below will work, make appropriate substitutions and save it with a .cmd extension.

@echo off 
C:
chdir C:\desired\directory
C:\full\path\of\command.exe

Put this batch file in a directory in your %PATH% and you should be able to invoke it from any cmd.exe instance.

Share:
110,353

Related videos on Youtube

Steve Guidi
Author by

Steve Guidi

Longtime software developer and amateur educator. I like to build stuff: software, hardware, and mechanical things are my favorites. In my spare time, I practice kendo. Come visit us at https://www.seattlekendo.org!

Updated on September 18, 2022

Comments

  • Steve Guidi
    Steve Guidi over 1 year

    If I run a program on the command line whose location is resolved through the Path environment variable, the program's working directory is generally set to its installation directory.

    I would like to run such a program from a console window and set its working directory to the current or other explicit directory. I was able to do this by temporarily copying the program to my working directory -- is there another way to accomplish this within the cmd.exe or powershell.exe environments?

    The windows shell analogy to this task is to create a shortcut and set the "Start In" property accordingly.

  • MBraedley
    MBraedley about 12 years
    Note that funkiness may occur if the working directory and executable aren't on the same partition/drive.
  • Pacerier
    Pacerier about 8 years
    @LawrenceC, However this solution requires a temporary file. It's better if this could be achieved using no temporary files