Necesita ayuda para crear un archivo por lotes para cambiar el nombre de varias carpetas

Necesita ayuda para crear un archivo por lotes para cambiar el nombre de varias carpetas

Tengo más de 12.000 carpetas a las que me gustaría cambiarles el nombre con los primeros 12 caracteres del primer archivo dentro de cada carpeta. Por ejemplo, tengo una carpeta llamada "1" pero dentro hay varios archivos PDF y el primero de la lista tiene un nombre de archivo "201405090360.pdf". Quiero que se cambie el nombre de la carpeta, "201405090360", ¿es posible?

Respuesta1

Se reconoció que lo siguiente había ayudado. Podría mejorarse con un mayor manejo de errores, pero debería funcionar o usarse como punto de partida para un script más completo.

Notas:

El script VBScript debe estar en el mismo directorio que la carpeta principal según la vista de árbol a continuación.

La variable strPath en la parte superior debe cambiarse al nombre del directorio principal, es decir, cambiarse de "Inicio"

Cambie blnDoIt de falso a verdadero para realizar cambios.

Sugiera ejecutarlo primero de la siguiente manera: cscript process.vbs > log.txt

Si el archivo de registro parece correcto, cambie blnDoIt a verdadero.

' Given this structure:
'
'│   process.vbs
'│
'└───Start
'    ├───1
'    │       123456789012aaa.txt
'    │       123456789013bbb.txt
'    │
'    ├───2
'    │       223456789012ccc.txt
'    │       223456789013ddd.txt
'    │
'    ├───3
'    │       323456789012eee.txt
'    │       323456789013fff.txt
'    │
'    ├───4
'    │       423456789012ggg.txt
'    │       423456789013hhh.txt
'    │
'    ├───5
'    │       523456789012iii.txt
'    │       523456789013jjj.txt
'    │
'    └───6
'            623456789013kkk.txt
'            623456789012jjj.txt

'===================================================================================    

dim strPath : strPath = "Start"
dim blnDoIt : blnDoIt = false

'===================================================================================
dim objFSO                  : set objFSO = CreateObject("Scripting.FileSystemObject")
dim objFolder               : set objFolder = objFSO.GetFolder(strPath)
dim strPGetAbsolutePathName : strPGetAbsolutePathName = objFSO.GetAbsolutePathName(strPath)
dim colSubfolders           : set colSubfolders = objFolder.Subfolders

'===================================================================================
for each objSubfolder in colSubfolders
    strNameOfFolder = objSubfolder.Name

    wscript.echo "Processing directory: " & strNameOfFolder
    strFileNameToUse = GetFileNameToUseAsParentDir (strNameOfFolder)

    if strFileNameToUse <> -1 then

      wscript.echo " > Chosen file to represent directory: " & strFileNameToUse
      strLeft12 = left (strFileNameToUse, 12)
      wscript.echo " > First 12 characters of file: " & strLeft12

      if blnDoIt then
        wscript.echo " > Renaming directory " & strPGetAbsolutePathName & "\" & strNameOfFolder & " to " & strPGetAbsolutePathName & "\" & strLeft12
        objFSO.MoveFolder strPGetAbsolutePathName & "\" & strNameOfFolder, strPGetAbsolutePathName & "\" & strLeft12
      else
        wscript.echo " > Rename directory " & strPGetAbsolutePathName & "\" & strNameOfFolder & " to " & strPGetAbsolutePathName & "\" & strLeft12
      end if

    else
    wscript.echo " > Skipping."
    end if

    wscript.echo ""
next
'===================================================================================

'===================================================================================
Function GetFileNameToUseAsParentDir(strDir)

    dim oFiles : Set oFiles = CreateObject("System.Collections.ArrayList")

    dim oF : set oF = objFSO.GetFolder(strPGetAbsolutePathName & "\" & strDir).Files

    wscript.echo " > " & oF.count & " files in directory."

    if oF.count > 0 then

      for each oFile In oF
        oFiles.Add oFile.name
      next

      oFiles.Sort

      GetFileNameToUseAsParentDir = oFiles(0)

    else
      GetFileNameToUseAsParentDir = -1
    end if

    set oFiles = nothing

End Function
'===================================================================================

Respuesta2

Yo usaría Powershell. Si entendí sus especificaciones correctamente, esto debería funcionar:

# Get List of subfolders
$Folders = Get-ChildItem <FOLDER> -Directory
# Process each subfolder
Foreach ($Subfolder in $Folders){
     # Get the names all files in current subfolder
     $FileNames = (Get-ChildItem $Subfolder.FullName -File).Name
     # If folder was not empty
     if ($FileNames) {
         # Replace current name of folder with first 12 chars of the name of the first file 
         Rename-Item $Subfolder.FullName $FileNames[0].Substring(0,12) -WhatIf
    }
}

Reemplácela con su carpeta real, guárdela como archivo *.ps1, abra un PowerShell y ejecútelo.

Solo mostrará los resultados, no cambiará nada hasta que elimine "-Whatif" de la tercera línea desde abajo.

información relacionada