Mr Mystery Guest
Mr Mystery Guest

Reputation: 1474

Change to directory using variable name

I've written a script to search for a shape file (.shp), I want to change to that directory once found: Here's what I have

 FOR /F %%X IN ('DIR /S /B *.shp') DO SET shapefolder=%%~DPNX
 IF DEFINED shapefolder (
 ECHO %shapefolder%
 CD /d shapefolder REM doesn't work
 ) ELSE (
 ECHO File not found
 )

What am I missing?

Upvotes: 0

Views: 47

Answers (2)

SomethingDark
SomethingDark

Reputation: 14305

Two things are wrong with your code. The first, as Oliver already pointed out, is that cd /d shapefolder should be cd /d %shapefolder% so that you're calling the actual variable.

The other thing is that SET shapefolder=%%~DPNX should beSET shapefolder=%%~DPX instead.

This is because the N refers to the filename of the file it finds, so if you have a square.shp, your code currently will look for C:\files\shapes\square instead of C:\files\shapes\ like it's supposed to.

Upvotes: 1

Oliver
Oliver

Reputation: 45101

Just add the percent sign to your variable in the cd command:

CD /d %shapefolder%

Upvotes: 0

Related Questions