Windows execute command in current directory

Batch script to execute some commands in each sub-folder

I need to write a script to work in Windows, that when executed will run a command in some of sub-directories, but unfortunately I have never done anything in batch, and I don’t know where to start.

With the example structure of folders:

I want the script to enter the specified folders (e.g. only ‘one’ and ‘four’) and then run some command inside every child directories of that folders.

If you could provide any help, maybe some basic tutorial or just names of the commands I will need, I would be very grateful.

5 Answers 5

You can tell the batch to iterate directories:

Use a percent sign when run directly on the command line, two when run from a batch

In a batch this would look something like this:

Put the commands you need in the lines between ( and ) . If you replace C:\temp\ with %1 you can tell the batch to take the value of the directory from the first parameter when you call it. Depending of the amount of directories you then either call the batch for each directory or read them from a list:

The paths.lst will look like this:

All of this is written from memory, so you might need to add some quotations marks 😉 Please note that this will only process the first level of directories, that means no child folders of a selected child folder.

You should take a look at this. The command you are looking for is FOR /R . Looks something like this:

I like answer of Marged that has been defined as BEST answer (I vote up), but this answer has a big inconvenience.

When DOS command between ( and ) contains some errors, the error message returned by DOS is not very explicit.

For information, this message is

To avoid this situation, I propose the following solution :

The FOR loop call $DoSomething «method» for each directory found passing DIR-NAME has a parameter. Caution: doublequote are passed to %1 parameter in $DoSomething method.

The exit /B command is used to indicate END of method and not END of script.

The result on my PC where I have 2 folders in c:\Temp folder is

Caution: in Marged s answer, usage of cd «%%i» is incorrect when folder is relative (folder with . or ..).

Why, because the script goto first folder and when it is in first folder it request to goto second folder FROM first folder !

How can Bash execute a command in a different directory context?

I have a common command that gets called from within very specific directories. There is only one executable sitting in /bin for this program, and the current working directory is very important for running it correctly. The script affects the files that live inside the directory it is run within.

Now, I also have a custom shell script that does some things in one directory, but I need to call that command mentioned above as if it was in another directory.

How do you do this in a shell script?

4 Answers 4

You can use the cd builtin, or the pushd and popd builtins for this purpose. For example:

You use the builtins just like any other command, and can change directory context as many times as you like in a script.

Use cd in a subshell; the shorthand way to use this kind of subshell is parentheses.

That said, if your command has an environment that it requires, it should really ensure that environment itself instead of putting the onus on anything that might want to use it (unless it’s an internal command used in very specific circumstances in the context of a well defined larger system, such that any caller already needs to ensure the environment it requires). Usually this would be some kind of shell script wrapper.

If you want to return to your current working directory:

  1. We are setting a variable current_dir equal to your pwd
  2. after that we are going to cd to where you need to run your command
  3. then we are running the command
  4. then we are going to cd back to our variable current_dir
Читайте также:  Windows server 2012 r2 standard установка с флешки

Another Solution by @apieceofbart pushd && YOUR COMMAND && popd

Windows shell command to get the full path to the current directory?

Is there a Windows command line command that I can use to get the full path to the current working directory?

Also, how can I store this path inside a variable used in a batch file?

14 Answers 14

Use cd with no arguments if you’re using the shell directly, or %cd% if you want to use it in a batch file (it behaves like an environment variable).

You can set a batch/environment variable as follows:

sample screenshot from a Windows 7 x64 cmd.exe.

Update: if you do a SET var = %cd% instead of SET var=%cd% , below is what happens. Thanks to jeb.

Quote the Windows help for the set command ( set /? ):

Note the %CD% — expands to the current directory string. part.

This has always worked for me:

For Windows we can use

command is there.

For Windows, cd by itself will show you the current working directory.

For UNIX and workalike systems, pwd will perform the same task. You can also use the $PWD shell variable under some shells. I am not sure if Windows supports getting the current working directory via a shell variable or not.

On Windows:

CHDIR Displays the name of or changes the current directory.

In Linux:

PWD Displays the name of current directory.

Based on the follow up question (store the data in a variable) in the comments to the chdir post I’m betting he wants to store the current path to restore it after changeing directories.

The original user should look at «pushd», which changes directory and pushes the current one onto a stack that can be restored with a «popd». On any modern Windows cmd shell that is the way to go when making batch files.

If you really need to grab the current path then modern cmd shells also have a %CD% variable that you can easily stuff away in another variable for reference.

BAT file to open CMD in current directory

I have many scripts which I interact with from the command line. Everytime I need to use them, I have to open a command line window and copy+paste and CD to the path to the directory they are in. This is tedious (they are in a rather deep file system, so typing out the full path is a pain, copy+paste is better but not much). I tried to create a .BAT file that I could double-click on that would open a new command-line window in the folder the .bat file exists in but it does not work. It opens a new window, but the working directory is not the directory that .bat file is in. Here’s what I’ve got after much googling (My cmd skills ain’t so great):

I know from when I used Linux that Konqueror had a «Command-line window here» feature, and that’s the effect I’m trying to get on Windows.

18 Answers 18

Create a file named open_dos_here.cmd with the following lines:

Put this file at any folder. Then, go to your Send To folder ( Win + E ; Alt + D ; shell:sendto ; Enter ). Create a shortcut to point to this open_dos_here.cmd

Then, in any folder, select any file or sub-folder. Right-click and select «Send To» and then select open_dos_here.cmd to open the DOS in that folder.

p1″ – Alvin SIU Dec 19 ’10 at 15:33

d1 is to extract only the drive letter of %1 (e.g. C:). This goes to C drive. The 2nd line cd to %

p1 which is the path of %1 (i.e. \myFolder). After going to this directory, simply call the cmd to open the DOS command prompt. – Alvin SIU Aug 23 ’14 at 9:12

you probably want to do this:

this will set your current directory to the directory you have the batch file in

dp0′ is simply the variable that holds the path the currently executing batch file is located in — therefore executing this command will take you to that directory (apparently this variable is only available from a batch file, which makes sense) – Chris Dec 15 ’10 at 15:51

dp0″ With the double-quotes? – Paul Tomasi Dec 19 ’10 at 3:59

dp0′ – Chris Jan 11 ’11 at 15:23

You can just enter cmd into the address bar in Explorer and it starts up in that path. Likewise for PowerShell.

There’s more simple way

As a more general solution you might want to check out the Microsoft Power Toy for XP that adds the «Open Command Window Here» option when you right-click: http://www.microsoft.com/windowsxp/downloads/powertoys/xppowertoys.mspx

In Vista and Windows 7, you’ll get that option if you hold down shift and right-click (this is built in).

Читайте также:  Как изменить язык меню пуск windows 10

I’m thinking that if you are creating a batch script that relies on the Current Directory being set to the folder that contains the batch file, that you are setting yourself up for trouble when you try to execute the batch file using a fully qualified path as you would from a scheduler.

Better to add this line to your batch file too:

unless you are fully qualifying all of your paths.

The simplest command to do this:
start

You can always run this in command line to open new command line window in the same location. Or you can place it in your .bat file.

Most simple way in explorer is to Shift + right mouse click on the folder or on an empty space in the folder and click on Open command prompt here .

CMD will then start in that folder

I must say, I’m not sure if it works for Windows Vista and below, but it surely works for Windows 7, 8, 8.1 and 10.

Another solution is to use a shortcut file to cmd.exe instead of a batch file.

Edit the shortcut’s start in property to %

You achieve the same thing, except it has the Cmd icon (and you can change this).

Some people don’t like clicking on batch files without knowing what’s in them, and some corporate network drives have a ban on .bat files.

You could add a context menu entry through the registry:

Navigate in your Registry to HKEY_LOCAL_MACHINE/Software/Classes/Folder/Shell and create a key called «Command Prompt» without the quotes.

Set the default string to whatever text you want to appear in the right-click menu.

Create a new key within your newly created command prompt named «command,» and set the default string to

You may need to add %SystemRoot%\system32\ before the cmd.exe if the executable can’t be found.

  1. The changes should take place immediately. Right click a folder and your new menu item should appear.

Referring to answer of @Chris,

We can also go to parent directory of batch file and run commands using following

To understand working of command cd /d %

dp0.. please refer below link

A bit late to the game but if I’m understanding your needs correctly this will help people with the same issue.

Two solutions with the same first step: First navigate to the location you keep your scripts in and copy the filepath to that directory.

  • Click «Start»
  • Right-click «Computer» (or «My Computer)
  • Click «Properties»
  • On the left, click «Advanced System Settings»
  • Click «Environment Variables»
  • In the «System Variables» Box, scroll down and select «PATH»
  • Click «Edit»
  • In the «Variable Value» field, scroll all the way to the right
  • If there isn’t a semi-colon (;) there yet, add it.
  • Paste in the filepath you copied earlier.
  • End with a semi-colon.
  • Click «OK»
  • Click «OK» again
  • Click «OK» one last time

You can now use any of your scripts as if you were already that folder.

Second Solution: (can easily be paired with the first for extra usefulness)

On your desktop create a batch file with the following content.

This will open a command window like what you tried to do.

Command Prompt: 11 basic commands you should know (cd, dir, mkdir, etc.)

Geeks and experts love the Command Prompt because of the advanced commands it can run. Fortunately, Command Prompt is not built only on advanced commands, but also on simple ones, designed to perform basic operations. In this article, we show you how to execute commands such as changing the current directory, switching to another drive, viewing the contents of a directory, creating and renaming folders, copying, deleting files and folders, and launching applications from the Command Prompt. We are also going to show you how to get help when using this app for Windows. Let’s get started:

NOTE: The information shared in this tutorial applies to Windows 10, Windows 8.1, and Windows 7. Note that, for simplicity, we are using screenshots taken only in Windows 10.

1. How to change the directory (folder) in Command Prompt (CMD)

The first command from the list is CD (Change Directory). This command enables you to change the current directory or, in other words, to navigate to another folder from your PC. For instance, the command CD takes you to the top of the directory tree. To see how it works, after you open the Command Prompt, type cd and press Enter on your keyboard. You should see how the CD command takes you to the top of the directory tree. In this case, to the “C:” drive.

Note that the Command Prompt is not case sensitive, meaning that you can type commands using capital letters, lowercase or any combination of them. The commands CD, cd or Cd, all work the same way.

Читайте также:  Windows phone store для компьютера

Going back to the “CD” command, now you are working on the root of the “C:” drive. If you need to go to a specific folder from this drive run the command “CD Folder.” The subfolders must be separated by a backslash character: “.” For instance, when you need to access the System32 folder located in “C:\Windows,” type “cd windows\system32” as shown below, and then press Enter on your keyboard.

When you need to go one folder up, use the “cd..” command. Let’s assume that you want to go back to the Windows folder. Type “cd..” and press Enter on your keyboard.

The effect is that your current directory changes to “C:\Windows.”

2. How to change the drive in Command Prompt (CMD)

To access another drive, type the drive’s letter, followed by “:”. For instance, if you wanted to change the drive from “C:” to “D:”, you should type “d:” and then press Enter on your keyboard.

To change the drive and the directory at the same time, use the cd command, followed by the “/d” switch. The “/d” parameter is used to change the current drive to a specific folder from another disk volume.

For instance, if you are now on the “D:” drive and you want to go back to the Windows folder from the”C:” drive, you should type “cd /d C:\Windows” and press Enter on your keyboard, like in the following screenshot.

NOTE: By typing only the drive letter you automatically move to your most recent location on that drive. For instance, if you are on “D:” drive and type “cd c:\windows” nothing seems to happen. However, if you type “c:” then the working folder changes to “c:\windows,” assuming that it was the last folder you worked with on your “C:” drive.

3. How to view the contents of a directory in Command Prompt (CMD)

You can view the contents of a folder by using a command called DIR. To test it, we have created a folder named Digital_Citizen on the D: drive, with several files and subfolders. You can see them in the screenshot below.

The last time, our working folder was “C:\Windows.” To navigate to the folder mentioned above, we have to use the command “cd /d D:\Digital_Citizen.” To view the contents of the folder, type DIR, and press Enter. The list of the files and folders contained by it is displayed, together with some details about each of them (the size and the date and time when they were last modified).

4. How to create a new directory with Command Prompt (CMD)

You can make a new folder using the MKDIR (Make Directory) or the MD command. The syntax of these commands is “MKDIR Folder” or “MD Folder.”

Let’s say we need to create a new folder called Digital_Citizen_Life that is going to be placed in the “D:\Digital_Citizen” folder. To do that, we need to type “mkdir Digital_Citizen_Life” and then press Enter, as shown below.

To test if it worked, use the DIR command again. The newly created folder appears in the list.

NOTE: Do not forget that all these commands depend on the current location in the Command Prompt. For instance, if you are on the “C:” drive and type “MKDIR test,” the new folder is created in the root of the “C:” drive.

Another way to create a folder that does not involve being in the desired folder is to type the complete path of the new folder. For example, if you are working on the “D:” drive and you want to create a new folder in “C:,” called other_stuff, type “mkdir c:\other_stuff” and then press Enter.

When you need to create a folder with subfolders at the same time, you can use the “MKDIR FolderSubfolder” command. For instance, if we type “mkdir Digital_Citizen_Tests\Beta\Test1” three folders are created: Digital_Citizen_Tests, Beta and Test1, in a tree-like structure.

5. How to rename files and folders with Command Prompt (CMD)

To rename files and folders, you need to use the REN (Rename) command. To rename folders, type “ren Folder NewFolderName.” For example, if we wanted to rename the Digital_Citizen_Tests folder to Digital_Citizen_Final_Tests, we should run “ren Digital_Citizen_Tests Digital_Citizen_Final_Tests” and press Enter.

To rename a file, use the same command, like this: “ren filename.extension newname.extension”. For instance, to rename the Digital_Citizen_Picture1.bmp file to Image0.bmp, we have to run the command “ren Digital_Citizen_Image1.bmp Image0.bmp” command.

Read the second page of this tutorial if you want to learn how to copy files and folders, delete files and folders, start an application, and get help when using the Command Prompt.

Оцените статью