Avatar of E=mc2
E=mc2
Flag 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?
Windows 10Windows Batch

Avatar of undefined
Last Comment
McKnife

8/22/2022 - Mon
ITguy565

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
oBdA

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
McKnife

copy somefile .\somefolder_next_to_this_batch\

Open in new window

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

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
McKnife

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.