We help IT Professionals succeed at work.

Specifying immediate parent folder in a batch file

E=mc2
E=mc2 asked
on
119 Views
Last Modified: 2020-10-26
Within a batch file, I would like to tell the batch to copy the files to the folder which is found just outside where the batch is running.
Is there a command that will allow this to happen?
Comment
Watch Question

CERTIFIED EXPERT

Commented:
This should answer that question :

reference : https://wiert.me/2011/08/09/batch-files-getting-directory-and-parent-directory/

[quote]echo batchfile=%0
  echo full=%~f0
setlocal
  set Directory=%~dp0
echo Directory=%Directory%
:: strip trailing backslash
  set Directory=%Directory:~0,-1%
echo %Directory%
::  ~dp does not work for regular environment variables:
::  set ParentDirectory=%Directory:~dp%  set ParentDirectory=%Directory:~dp%
::  ~dp only works for batch file parameters and loop indexes
  for %%d in (%Directory%) do set ParentDirectory=%%~dpd
  echo ParentDirectory=%ParentDirectory%
endlocal[/quote]

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
copy somefile .\somefolder_next_to_this_batch\

Open in new window

CERTIFIED EXPERT
Most Valuable Expert 2019
Most Valuable Expert 2018

Commented:
McKnife,
for one thing, that might target the batch script's current folder under the right conditions, but not its parent (see the title, it's not so clear in the question.
But more importantly, this would target the current working directory, but not the script folder. They might be the same, but this is not a given.
Save this as C:\Temp\Whatever.cmd
Open a command prompt, use "cd C:\" to change to the root of the drive (or change to any other folder that is not C:\Temp) , then run
C:\Temp\Whatever.cmd
to see the difference (assumes an English Windows version).
echo Working directory using '.':
dir /a:d .\*.foo 2>NUL | find "Directory"
echo Script folder using %%~dp0:
dir /a:d %~dp0*.foo 2>NUL | find "Directory"

Open in new window

CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
Yes. I have no doubt that your solution is better. It's just my way of throwing in a one-liner that some people who (possibly) don't even know the meaning of .\ might find interesting, short and handy. Anything needs testing, even a one-liner.