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!

  • 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. – Ƭᴇcʜιᴇ007 Apr 30 '14 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. – Vergentorix Apr 30 '14 at 16:28
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"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.