Question

I have a script that copies several PDF Files, and it places it to the corresponding folder.

Script:

pushd "\\share\folder\"
for %%p in (*.pdf) do for /f "tokens=1 delims=_" %%n in ("%%~np") do (
    copy "%%~fp" "\\share2\folder\%%~n\%%~nxp"
)

But it also copies files that are named like this: Test.pdf2098 or hello.pdf20j93f2

I just want it to copy *.pdf files and not PDF's that are invalid.

Was it helpful?

Solution

Add an if check to verify the extension

pushd "\\share\folder\"
for %%p in (*.pdf) do if /i ".pdf"=="%%~xp" for /f "tokens=1 delims=_" %%n in ("%%~np") do (
    copy "%%~fp" "\\share2\folder\%%~n\%%~nxp"
)

OTHER TIPS

David Ruhmann provided a workaround, but did not explain why your code fails.

The problem is that files on NTFS volumes that do not meet the old 8.3 short file naming standard are automatically assigned alternate short file names that do meet the standard. Files like xxx.pdf2098 would be given a short name that has a .pdf extension.

The windows commands like COPY, MOVE, FOR, etc. that search file names all attempt to match both the long and the short name, thus leading to your problem.

It is possible (and often recommended) to disable short file name generation on NTSF volumes, but any existing short names will remain and potentially still cause problems.

So David Ruhmann is correct in suggesting that you verify the file extension of each file.

Another frequently used method to verify the extension is to pipe DIR /B to FINDSTR:

for /f "eol=: delims=" %%p in (
  'dir /a-d /b *.pdf^|findstr /lie ".pdf"'
) do for /f "tokens=1 delims=_" %%n in ("%%~np") do (
  copy "%%~fp" "\\share2\folder\%%~n\%%~nxp"
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top