Search code examples
batch-filerenameregexp-replacebatch-rename

Rename file and move to folder Powershell


I have some PDF files that I need to rename and move to specific folders to be able to import into a system. The file by default has the following name: ex: 12345.123456/1234-12.pdf

First I need to remove the characters "," "/" "-"

@echo off
setlocal EnabledelayedExpansion
for /r "C:\importation" %%a in (*) do (
set "newname=%%~na"
set "newname=!newname:.=!"
set "newname=!newname:-=!"
set "newname=!newname:/=!"
ren "%%~a" "!newname!%%~xa"
)

Now I need to create folders with the filename (without the characters removed, ex: 12345123456123412) and rename them to the following pattern: ex: P12345123456123412_V1_A0V0_T07-54-369-664_S00001_Volume.pdf

For that I drag the files to the following script:

@If Not "%~1" == "" For %%G In (%*) Do @MD "%%~dpG%%~nG" 2>NUL && Move /Y "%%~G" "%%~dpG%%~nG\P%%~nG_V1_A0V0_T07-54-369-664_S00001_Volume%%~xG"

I would like to do only one process, that is, join the two scripts and run only once. Can someone help me?

Rather than dragging the files to the batch file I would like to run it and have it read the files (.pdf) from the folder


Solution

  • Is something like this what you are looking for?

    The following will accept drag and drop of one or more files or directories, (subject to command line length restrictions). Each individually dropped PDF file and each PDF file within any dropped directory should be processed as requested.

    @Echo Off
    SetLocal EnableExtensions DisableDelayedExpansion
    If "%~1" == "" GoTo :EOF
    For %%G In (%*) Do (For %%H In ("%%~G") Do If "%%~aH" Lss "-" (
            Echo Error! %%G no longer exists.
            %SystemRoot%\System32\timeout.exe /T 2 /NoBreak 1>NUL
        ) Else If "%%~aH" GEq "d" (For %%I In ("%%~G\*.pdf") Do Call :Sub "%%~I"
        ) Else If /I "%%~xG" == ".pdf" (Call :Sub "%%~G"
        ) Else (Echo Error! %%G is not a PDF
            %SystemRoot%\System32\timeout.exe /T 2 /NoBreak 1>NUL))
    GoTo :EOF
    
    :Sub
    Set "basename=%~n1"
    Set "basename=%basename:.=%"
    MD "%~dp1%~n1" 2>NUL
    If Not ErrorLevel 1 Move /Y %1 "%~dp1%~n1\P%basename:-=%_V1_A0V0_T07-54-369-664_S00001_Volume%~x1"
    Exit /B
    

    Please note, as the character / is invalid in file or directory names, I have ignored that part of your question.