How do i get folder name of variable in batch script?

I'm have a Windows batch script with a variable like this:

SET SOURCE=C:\user\folder1

How do I pull out just the folder name "folder1" from %SOURCE%?
bemara57Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

knightEknightCommented:
Here is how to do it with that exact folder name -- I'm working on a way to make it more generic:

@echo off
SET SOURCE=C:\user\folder1
for /f "tokens=1-3 delims=\" %%D in ('@echo %SOURCE%') do set SUBFOLDER=%%F
echo %SUBFOLDER%
0
knightEknightCommented:
Got it!  This will work with a path of any length:

@echo off
SET SOURCE=C:\user\folder1
for /f %%D in ('@echo %SOURCE:\=.%') do set SUBFOLDER=%%~xD
set SUBFOLDER=%SUBFOLDER:.=%
echo %SUBFOLDER%
0
knightEknightCommented:
... removing the space delimiter so that folder names with spaces will also work:

@echo off
SET SOURCE="C:\user\folder1\subfolder2\subfolder3"
for /f "delims=" %%D in ('@echo %SOURCE:\=.%') do set SUBFOLDER=%%~xD
set SUBFOLDER=%SUBFOLDER:.=%
echo %SUBFOLDER%
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Steve KnightIT ConsultancyCommented:
I have this one in my toolkit:

@echo off
set source=%cd%
set folder=
for /f "tokens=*" %%a in ("%source%") do set folder=%%~na
echo The users folder name is %folder%

Replace the %cd% (current directory) with your c:\user\folder1 etc.

Of course if your script already sets

SET SOURCE=C:\user\folder1

Why not do it like this:

SET USERFOLDER=folder1
SET SOURCE=c:\user\%USERFOLDER%

Steve
0
Steve KnightIT ConsultancyCommented:
thanks for the split of points.

Steve
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Windows Batch

From novice to tech pro — start learning today.