Link to home
Start Free TrialLog in
Avatar of E=mc2
E=mc2Flag for Canada

asked on

Specifying immediate parent folder in a batch file

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?
Avatar of ITguy565
ITguy565
Flag of United States of America image

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

ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
copy somefile .\somefolder_next_to_this_batch\

Open in new window

Avatar of oBdA
oBdA

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

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.