Precisa de ajuda para criar um arquivo em lote para renomear várias pastas

Precisa de ajuda para criar um arquivo em lote para renomear várias pastas

Tenho mais de 12.000 pastas que gostaria de renomear com os primeiros 12 caracteres do primeiro arquivo dentro de cada pasta. Por exemplo, tenho uma pasta chamada "1", mas dentro dela existem vários arquivos PDF e o primeiro listado tem o nome de arquivo "201405090360.pdf". Quero que a pasta seja renomeada, "201405090360", isso é possível?

Responder1

O seguinte foi reconhecido como tendo ajudado. Ele poderia ser melhorado com mais tratamento de erros, mas deve funcionar ou ser usado como ponto de partida para um script mais completo.

Notas:

O script VBScript deve estar no mesmo diretório da pasta pai conforme a visualização em árvore abaixo.

A variável strPath no topo deve ser alterada para o nome do diretório pai, ou seja, alterada de "Iniciar"

Altere blnDoIt de falso para verdadeiro para realmente fazer alterações.

Sugira executá-lo primeiro da seguinte maneira: cscript process.vbs > log.txt

Se o arquivo de log parecer correto, altere blnDoIt para true.

' 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
'===================================================================================

Responder2

Eu usaria o Powershell. Se entendi suas especificações corretamente, isso deve 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
    }
}

Substitua pela sua pasta real, salve como arquivo *.ps1, abra um PowerShell e execute.

Irá exibir apenas os resultados, não alterará nada até que você remova "-Whatif" da terceira linha de baixo.

informação relacionada