1

Thanks in advance for your help with this.

I've been reading, experimenting, and banging my head against the wall for a couple days on this, and could really use some assistance. This is my first batch file attempt.

I'm trying to loop through .tif files in a folder and run a gdal process on them. I have been calling the .bat file via command line in the OsGeo4W terminal.

I can successfully run the gdal_polygonize process on individual files, but have not succeeded in running it iteratively.

SETLOCAL EnableDelayedExpansion

SET MYPATH = C:\Users\mkcarte2\Desktop\Polygonize\

FOR /F %%i IN ('DIR /B %MYPATH%*.tif') DO (

    SET MYPATHFILE=%%~nI ::Trying to parse only the filename, so that I don't stack extensions in the output file
    SET infile=%%i
    SET outfile=%MYPATHFILE%.shp!

    gdal_polygonize %MYPATH%!infile! -F  "ESRI Shapefile" %MYPATH%!outfile!
)

My Error Messages:

For first file:

Warning 1: Layer name 'ESRI Shapefile' adjusted to >'ESRIShapefile' for XML validity. Warning 1: Field name '%~nI.shp' adjusted to '_nI.shp' to be a >valid XML element name. 0...10...20...30...40...50...60...70...80...90...100 - done. For subsequent files:

Subsequent files:

ERROR 4: `!infile!' does not exist in the file system, and is not recognised as a supported dataset name. Unable to open !infile!

2
  • What's with the exclamation marks? Variables like infile should be referenced as %infile%, not !infile!? Perhaps !%infile%! if you need the exclamation marks. Also, perhaps try %%ni instead of %%nI. Commented Apr 30, 2014 at 15:22
  • As I understand it, the exclamation marks are necessary for delayed expansion. But I'm very new to this, so I could very well be wrong. Commented Apr 30, 2014 at 16:28

1 Answer 1

2

You have a few problems.

  • Your definition of MYPATH is wrong. Spaces are significant when doing SET assignments. You created a variable name with a space at the end and a value with a space in the front.

  • FOR variable names are case sensitive: %%i and %%I are not the same thing

  • SET outfile=%MYPATHFILE%.shp! would have to change to SET outfile=!MYPATHFILE!.shp

But your script can be simplified tremendously:

for %%F in ("C:\Users\mkcarte2\Desktop\Polygonize\*.tif") do (
  gdal_polygonize "%%F" "ESRI Shapefile" "%%~dpnF.shp"
)

Or you could run a simple one liner from the command line, without any script:

for %F in ("C:\Users\mkcarte2\Desktop\Polygonize\*.tif") do gdal_polygonize "%F" "ESRI Shapefile" "%~dpnF.shp"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .