- Batch file : How to get current directory
- GetCurrentDirectory function (winbase.h)
- Syntax
- Parameters
- Return value
- Remarks
- Windows shell command to get the full path to the current directory?
- 14 Answers 14
- Get current batchfile directory
- 4 Answers 4
- Управление текущим расположением Managing Current Location
- Получение текущего расположения (Get-Location) Getting Your Current Location (Get-Location)
- Настройка текущего расположения (Set-Location) Setting Your Current Location (Set-Location)
- Сохранение и отзыв последних расположений (Push-Location и Pop-Location) Saving and Recalling Recent Locations (Push-Location and Pop-Location)
Batch file : How to get current directory
Here’s a question from a blog reader.
“I need to write a batch script file which can traverse to different directories and do some operations on those directories. Once done, I need to come back to the original directory where the batch script started and do some more stuff. I need to get the initial starting directory and save it in a variable. My question is what’s the simple way to get the the directory from batch script. ”
Below is the answer for this question.
There is a very simple way to get the directory from a batch script file. CD environment variable stores the current directory of a command window session. Just run the command ‘echo %CD%’ and check it yourself.
Another way to do what the reader wanted would be to use the pushd and popd commands to traverse directories like a stack.
outputs blank empty line
If you traverse the flag of the 7th decimal variable. The channel of corresponding flag will stay static in the field of the command to enable what you need
How to create a batch file that can organise files into specific folders that have been downloaded from the internet.
Example; if I was to download a number of different file types such as a pdf, mp4,mp3, or an app, they would normally download into the download file by default. I would like to take the many different file types in the download folder and organise them into specific folders within my libraries by batching them. Can this be done?
You can download all the files into the default folder. Next, create a subfolder for each of the file type you have. Next, run the command below.
GetCurrentDirectory function (winbase.h)
Retrieves the current directory for the current process.
Syntax
Parameters
The length of the buffer for the current directory string, in TCHARs. The buffer length must include room for a terminating null character.
A pointer to the buffer that receives the current directory string. This null-terminated string specifies the absolute path to the current directory.
To determine the required buffer size, set this parameter to NULL and the nBufferLength parameter to 0.
Return value
If the function succeeds, the return value specifies the number of characters that are written to the buffer, not including the terminating null character.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
If the buffer that is pointed to by lpBuffer is not large enough, the return value specifies the required size of the buffer, in characters, including the null-terminating character.
Remarks
Each process has a single current directory that consists of two parts:
- A disk designator that is either a drive letter followed by a colon, or a server name followed by a share name (\\servername\sharename)
- A directory on the disk designator
To set the current directory, use the SetCurrentDirectory function.
Multithreaded applications and shared library code should not use the
GetCurrentDirectory function and should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. This limitation also applies to the SetCurrentDirectory and GetFullPathName functions. The exception being when the application is guaranteed to be running in a single thread, for example parsing file names from the command line argument string in the main thread prior to creating any additional threads. Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.
In WindowsВ 8 and Windows ServerВ 2012, this function is supported by the following technologies.
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.
Get current batchfile directory
Firstly, I saw this topic but I couldn’t understand that.
Question :
There is a batch file in D:\path\to\file.bat with following content :
It must be D:\path\to
What am I doing wrong?
4 Answers 4
System read-only variable %CD% keeps the path of the caller of the batch, not the batch file location.
You can get the name of the batch script itself as typed by the user with %0 (e.g. scripts\mybatch.bat ). Parameter extensions can be applied to this so %
dp0 will return the Drive and Path to the batch script (e.g. W:\scripts\ ) and %
f0 will return the full pathname (e.g. W:\scripts\mybatch.cmd ).
You can refer to other files in the same folder as the batch script by using this syntax:
This can even be used in a subroutine, Echo %0 will give the call label but, echo «%
nx0″ will give you the filename of the batch script.
When the %0 variable is expanded, the result is enclosed in quotation marks.
dp0 will return path to batch location. echo %
f0 will return path to the batch with filename. – Stoleg Jun 12 ’13 at 12:03
dp0 ? – Ivailo Bardarov May 5 ’17 at 10:06
dp0 as first line of batch file and worked – mkb Oct 25 ’17 at 4:03
dp0″ rather than %
dp0 . Quotes will guarantee the path is taken as one token, even if there are spaces, and also protects against poison characters like & . – dbenham Dec 20 ’19 at 3:53
Within your .bat file:
You can now use the variable %mypath% to reference the file path to the .bat file. To verify the path is correct:
For example, a file called DIR.bat with the following contents
run from the directory g:\test\bat will echo that path in the DOS command window.
Here’s what I use at the top of all my batch files. I just copy/paste from my template folder.
Setting current batch file’s path to %batdir% allows you to call it in subsequent stmts in current batch file, regardless of where this batch file changes to. Using PUSHD allows you to use POPD to quickly set this batch file’s path to original %batdir%. Remember, if using %batdir%ExtraDir or %batdir%\ExtraDir (depending on which version used above, ending backslash or not) you will need to enclose the entire string in double quotes if path has spaces (i.e. «%batdir%ExtraDir»). You can always use PUSHD %
dp0. [https: // ss64.com/ nt/ syntax-args .html] has more on (%
Note that using (::) at beginning of a line makes it a comment line. More importantly, using :: allows you to include redirectors, pipes, special chars (i.e. | etc) in that comment.
Of course, Powershell does this and lots more.
Управление текущим расположением Managing Current Location
При навигации по системам папок в проводнике у вас обычно есть определенное рабочее расположение, т. е. текущая открытая папка. When navigating folder systems in File Explorer, you usually have a specific working location — namely, the current open folder. Элементами в текущей папке можно легко управлять, щелкая их. Items in the current folder can be manipulated easily by clicking them. Когда в интерфейсе командной строки (например, Cmd.exe) открыта папка, в которой находится определенный файл, вы можете получить к нему доступ, указав короткое имя, а не вводить весь путь к файлу. For command-line interfaces such as Cmd.exe, when you are in the same folder as a particular file, you can access it by specifying a relatively short name, rather than needing to specify the entire path to the file. Текущий каталог называется рабочим. The current directory is called the working directory.
Windows PowerShell использует существительное Location для ссылки на рабочий каталог и реализует семейство командлетов для просмотра расположения и управления им. Windows PowerShell uses the noun Location to refer to the working directory, and implements a family of cmdlets to examine and manipulate your location.
Получение текущего расположения (Get-Location) Getting Your Current Location (Get-Location)
Чтобы определить путь к текущему каталогу, введите команду Get-Location : To determine the path of your current directory location, enter the Get-Location command:
Командлет Get-Location аналогичен команде pwd в оболочке BASH. The Get-Location cmdlet is similar to the pwd command in the BASH shell. Командлет Set-Location аналогичен команде cd в Cmd.exe. The Set-Location cmdlet is similar to the cd command in Cmd.exe.
Настройка текущего расположения (Set-Location) Setting Your Current Location (Set-Location)
Команда Get-Location используется с командой Set-Location . The Get-Location command is used with the Set-Location command. Команда Set-Location позволяет вам указать расположение текущего каталога. The Set-Location command allows you to specify your current directory location.
Обратите внимание, что после ввода команды вы не получите прямого отклика о действии команды. After you enter the command, you will notice that you do not receive any direct feedback about the effect of the command. Большинство команд Windows PowerShell, выполняющих действия, практически не создают выходных данных, так как выходные данные не всегда полезны. Most Windows PowerShell commands that perform an action produce little or no output because the output is not always useful. Чтобы проверить успешность внесения изменения в каталог при вводе команды Set-Location , включите параметр -PassThru при вводе команды Set-Location : To verify that a successful directory change has occurred when you enter the Set-Location command, include the -PassThru parameter when you enter the Set-Location command:
Параметр -PassThru можно использовать с некоторыми командами Set в Windows PowerShell для возврата сведений о результате в случае отсутствия выходных данных по умолчанию. The -PassThru parameter can be used with many Set commands in Windows PowerShell to return information about the result in cases in which there is no default output.
Вы можете указать пути относительно текущего расположения так же, как и в большинстве командных оболочек UNIX и Windows. You can specify paths relative to your current location in the same way as you would in most UNIX and Windows command shells. В стандартной нотации для относительных путей точка ( . ) представляет текущую папку, а две точки ( .. ) — родительский каталог текущего расположения. In standard notation for relative paths, a period ( . )represents your current folder, and a doubled period ( .. ) represents the parent directory of your current location.
Например, если вы находитесь в папке C:\Windows , точка ( . ) представляет C:\Windows , а две точки ( .. ) представляют C: . For example, if you are in the C:\Windows folder, a period ( . )represents C:\Windows and double periods ( .. ) represent C: . Текущее расположение можно изменить на корень диска C: путем ввода следующей команды: You can change from your current location to the root of the C: drive by typing:
Тот же метод работает в дисках Windows PowerShell, которые не являются дисками файловой системы, например HKLM: . The same technique works on Windows PowerShell drives that are not file system drives, such as HKLM: . В реестре в качестве расположения можно задать раздел HKLM\Software путем ввода следующего кода: You can set your location to the HKLM\Software key in the registry by typing:
После этого можно изменить расположение каталога на родительский каталог, который является корнем диска Windows PowerShell HKLM: с помощью относительного пути: You can then change the directory location to the parent directory, which is the root of the Windows PowerShell HKLM: drive, by using a relative path:
Вы можете ввести Set-Location или использовать любой из встроенных псевдонимов Windows PowerShell для Set-Location (cd, chdir, sl). You can type Set-Location or use any of the built-in Windows PowerShell aliases for Set-Location (cd, chdir, sl). Пример: For example:
Сохранение и отзыв последних расположений (Push-Location и Pop-Location) Saving and Recalling Recent Locations (Push-Location and Pop-Location)
При изменении расположения полезно отслеживать свое предыдущее расположение и иметь возможность вернуться к нему. When changing locations, it is helpful to keep track of where you have been and to be able to return to your previous location. Командлет Push-Location в Windows PowerShell создает упорядоченный журнал («стек») путей к каталогам, которые вы открывали, чтобы можно было вернуться на шаг назад по журналу путей к каталогу, используя дополнительный командлет Pop-Location . The Push-Location cmdlet in Windows PowerShell creates a ordered history (a «stack») of directory paths where you have been, and you can step back through the history of directory paths by using the complementary Pop-Location cmdlet.
Например, Windows PowerShell обычно запускается в корневом каталоге пользователя. For example, Windows PowerShell typically starts in the user’s home directory.
Слово стек имеет специальное значение во многих параметрах программирования, включая .NET Framework. The word stack has a special meaning in many programming settings, including .NET Framework. Например, в физическом стеке элементов последний элемент, помещенный в стек, является первым элементом, который можно извлечь из него. Like a physical stack of items, the last item you put onto the stack is the first item that you can pull off the stack. Добавление элемента в стек в разговорной речи называется «проталкиванием» элемента в стек. Adding an item to a stack is colloquially known as «pushing» the item onto the stack. Извлечение элемента из стека в разговорной речи называется «выводом» элемента из стека. Pulling an item off the stack is colloquially known as «popping» the item off the stack.
Чтобы передать текущее расположение в стек, а затем переместить его в папку локальных параметров, введите: To push the current location onto the stack, and then move to the Local Settings folder, type:
После этого можно передать расположение локальных параметров в стек и переместить его в папку Temp, введя следующее: You can then push the Local Settings location onto the stack and move to the Temp folder by typing:
Чтобы убедиться, что каталоги изменены, введите команду Get-Location : You can verify that you changed directories by entering the Get-Location command:
После этого можно перейти в последний открытый каталог, введя команду Pop-Location , и проверить изменение, введя команду Get-Location : You can then pop back into the most recently visited directory by entering the Pop-Location command, and verify the change by entering the Get-Location command:
Как и в случае с командлетом Set-Location , можно включить параметр -PassThru при вводе командлета Pop-Location , чтобы открыть указанный каталог: Just as with the Set-Location cmdlet, you can include the -PassThru parameter when you enter the Pop-Location cmdlet to display the directory that you entered:
Кроме того, можно использовать командлеты расположения с сетевыми путями. You can also use the Location cmdlets with network paths. Если у вас есть сервер FS01 с общей папкой Public, можно изменить расположение, введя If you have a server named FS01 with an share named Public, you can change your location by typing
Для изменения расположения на любой доступный диск можно использовать команды Push-Location и Set-Location . You can use the Push-Location and Set-Location commands to change the location to any available drive. Например, если у вас есть локальный дисковод компакт-дисков с буквой диска D, содержащий компакт-диск с данными, вы можете изменить расположение на дисковод компакт-дисков, введя команду Set-Location D: . For example, if you have a local CD-ROM drive with drive letter D that contains a data CD, you can change the location to the CD drive by entering the Set-Location D: command.
Если дисковод пуст, вы получите следующее сообщение об ошибке: If the drive is empty, you will get the following error message:
В интерфейсе командной строки проводник неудобно использовать для просмотра свободных физических дисков. When you are using a command-line interface, it is not convenient to use File Explorer to examine the available physical drives. Также в проводнике будут показаны не все диски PowerShell. Also, File Explorer would not show you the all of the Windows PowerShell drives. Windows PowerShell предоставляет набор команд для управления дисками Windows PowerShell, о которых речь пойдет далее. Windows PowerShell provides a set of commands for manipulating Windows PowerShell drives, and we will talk about these next.