Intentando cambiar el nombre de una gran cantidad de archivos .doc basándose en la primera línea de texto

Intentando cambiar el nombre de una gran cantidad de archivos .doc basándose en la primera línea de texto

Estaba intentando ayudar a un amigo que había recuperado una gran cantidad de datos, pero los metadatos se perdieron. Como la mayoría son artículos o recetas, ella cree que el título o la primera línea del texto serán suficientes para un nombre de archivo.

Quería intentar usar un script de PowerShell para... acceder/leer los archivos, tomar la primera línea (si es posible, definir una longitud de caracteres) y luego cambiar el nombre. Como... lea los primeros 10 caracteres y cambie el nombre del archivo.

Encontré este script, que parece ser para archivos .txt. ¿Es posible reelaborarlo para .doc y luego eliminar la parte sobre O y simplemente hacer que lea la primera línea y cambiarle el nombre con los primeros 10 caracteres leídos?

Cualquier ayuda sería muy apreciada. (disculpas si arruiné la publicación del guión)

$myFolderFullOfTextFiles = 'C:\recoveredDocs'
$linesToReadInEachTextFile = 5

$myTextFiles = Get-ChildItem -Path $myFolderFullOfTextFiles

foreach( $textFile in $myTextFiles )
{
$newName = ''

foreach( $line in $(Get-Content -Path $textFile.FullName -Head $linesToReadInEachTextFile) )
{
    if( $line -like 'O*' )
    {
       $newName = $textFile.DirectoryName + '\' + $line.Substring(0,6) + '.txt'
    }
}

try
{
    Write-Host $newName
    Rename-Item -Path $textFile.FullName -NewName $newName
}
catch
{
    Write-Host "Failed to rename $textFile."
}

}

También encontré este script. que está más centrado en .doc. Todo lo que necesito es... leer la primera línea de texto, cambiarle el nombre (con un límite razonable de caracteres, como los primeros 10 caracteres).

Set objWord = CreateObject("Word.Application")
objWord.Visible = True

Set objDoc = objWord.Documents.Open("C:\Scripts\Test.doc")

strText = objDoc.Paragraphs(1).Range.Text
arrText = Split(strText, vbTab)
intIndex = Ubound(arrText)
strUserName = arrText(intIndex)

arrUserName = Split(strUserName, " ")
intLength = Len(arrUserName(1))
strName = Left(arrUserName(1), intlength - 1)

strUserName = strName & ", " & arrUserName(0)

strText = objDoc.Paragraphs(2).Range.Text
arrText = Split(strText, vbTab)
intIndex = Ubound(arrText)

strDate = arrText(intIndex)
strDate = Replace(strDate, "/", "")

intLength = Len(strDate)
strDate = Left(strDate, intlength - 1)

strFileName = "C:\Scripts\" &  strUserName & " " & strDate & ".doc"

objWord.Quit

Wscript.Sleep 5000

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.MoveFile "C:\Scripts\Test.doc", strFileName

Respuesta1

Copie el siguiente código y créelo como un script de PowerShell nombrando el archivo con la extensión .ps1 (probado correctamente con PowerShell 4 en Windows 7; verifique su versión de PowerShell con "get-host|Select-Object version" o "$PSVersionTable.PSVersion")

 $word_app = New-Object -ComObject Word.Application     <# New word application #>
    $source = 'C:\recoveredDocs'    <# create the source variable #>
    $destination = 'C:\renamedDocs' <# create the destination variable #>

    if (!(Test-Path -path $destination)) {  <# check to see if destination folder exists #>
    New-Item -path $destination\ -type directory -Force  } <# create destination folder if it doesn't already exist #>
    echo 'checking files to convert...'

    <# filter for word .doc files only #>
    Get-ChildItem -Path $source -Filter *.doc? | ForEach-Object {
    if (!(Test-Path "$destination\$($_.BaseName).doc")) {   <# check to see if file is already in destination folder (Note. "!" is a PS Alias for "-Not") #>

    $document = $word_app.Documents.Open($_.FullName)   <# open word document #>

    $pattern = '[^a-zA-Z1234567890 ]'   <# create regex pattern of allowed characters #>

    $textstring = $document.range().text <# get the text string from the document #>

    $titlestring = $textstring -replace $pattern, ''    <# apply the regex pattern to eliminate the reserved characters #>

    $title = $titlestring.substring(0, [System.Math]::Min(10, $titlestring.Length)) <# limit the string to 10 characters #>

    $doc_strNewName = "$destination\$($title).doc"  <# create the new name and path for the doc #>

    echo "$($_.FullName) converted to  $doc_strNewName"

$document.SaveAs([ref] $doc_strNewName, [ref] 0)    <# save the document with new name and path #>

$document.Close()   <# close documnet #>

        }
    }

    echo "No More Files to Convert"

$word_app.Quit()    <# close the word application #>

información relacionada